简体   繁体   中英

unique_ptr - invalid pointer and segfault

I am learning a new C++11 standard and writing small game in SFML. I have followed code where I am trying to pass a pointer of a sprite to another object.

bool Game::detectCollision()
{
    std::unique_ptr<sf::Sprite> sprPtr1(&iPlayer.charSprite);
    return field.detectCollision(sprPtr1);
}

bool FieldElem::detectCollision(std::unique_ptr<sf::Sprite> charSprite)
{
    std::cout << "X: " << charSprite->getPosition().x << std::endl;
    return true;
}

This code compiles without warning and gives me following segfault during a runtime:

*** glibc detected *** ./game: munmap_chunk(): invalid pointer: 0x00007fffb8617d90 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x7eb96)[0x7f8694b37b96]
./game(_ZN2sf6SpriteD0Ev+0x24)[0x405772]

Why my pointer is invalid? I think I am missing some important detail regarding unique_ptr...

std::unique_ptr assumes sole ownership of the pointed-to object, and deletes the object when the unique_ptr goes out of scope. So after detectCollision returns, charSprite is deleted. Since you never actually allocated charSprite (but rather allocated iPlayer , with charSprite in it), that's not kosher.

It sounds like you don't actually want unique_ptr here. You don't intend to transfer ownership.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM