سؤال

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top