SFML community forums

Help => Window => Topic started by: sharky on September 12, 2019, 09:06:12 am

Title: Application crash after deleting unique_ptr with reference to renderWindow
Post by: sharky on September 12, 2019, 09:06:12 am
Hello,
I am creating simple application with SFML. Yesterday Ive found funny "bug".
In my program I create views i.e. "MainMenuView", "GameView". Each of them holds reference to renderWindow. Game controller holds view as unique_ptr. My application stuck when I pass reference of renderWindow to new "View" and then delete this unique_ptr.
I fixed this using shared_ptr instead of reference. Is this a known issue? Am I doing something wrong?
class mainMenuView : public IView
{
public:
mainMenuView (sf::RenderWindow& w) : window(w) {}
void draw(); // drawing main menu
private:
sf::RenderWindow& window;
}

class gameView : public IView
{
public:
gameView (sf::RenderWindow& w) : window(w) {}
void draw(); // drawing map, units etc...
private:
sf::RenderWindow& window;
}

class gameController
{
public:
gameController(sf::RenderWindow& w) : window(w)
{
  std::unique_ptr<mainMenuView > uiView(new mainMenuView (window));
  currentView_ = std::move(uiView);
}
void createGame()
{
std::unique_ptr<GameView> gView(new GameView(window)); // If I wouldn't store this unique_ptr anywhere the game will stop and It doesnt work anymore
}
private:
std::unique_ptr<IView> currentView;
sf::RenderWindow& window;
}

main()
{
sf::RenderWindow w();
gameController gc(w);
game loop
{
    gc->processSignals....
    gc->update.....
    gc->draw....
}
}
 
Remember that this is only pseudo-code.
Title: Re: Application crash after deleting unique_ptr with reference to renderWindow
Post by: eXpl0it3r on September 12, 2019, 12:50:56 pm
It's hard to really understand what your code does in detail with the given pseudo code.

I recommend to use C++17 std::make_unique factory to create std::unique_ptr so you don't have to manually call new.

Don't forget that unique/shared ptr aren't just to wrap pointers, but they also indicate the ownership model. Using shared_ptr just because a unique_ptr didn't work, indicates that your issue actually lies somewhere else.
Title: Re: Application crash after deleting unique_ptr with reference to renderWindow
Post by: Nexus on September 12, 2019, 01:59:43 pm
Maybe you could come up with a minimal complete example (https://en.sfml-dev.org/forums/index.php?topic=5559.msg36368#msg36368)?
Title: Re: Application crash after deleting unique_ptr with reference to renderWindow
Post by: sharky on September 13, 2019, 09:30:55 pm
Ok guys Ive found the bug :D
Ive been reseting unique_ptr that was still in use. Stupid bug.
Thank You