I’m new to c++ coming from c#. The following code is not working and I’m not sure what it needs. Any insight to help me understand why it isn’t working and what the appropriate changes it should have would be appreciated.
// GamePlayScreen derives from ScreenBase
std::unique_ptr<GameplayScreen> m_game(new GameplayScreen());
// MenuScreen derives from ScreenBase
std::unique_ptr<MenuScreen> m_menu(new MenuScreen());
// PauseScreen derives from ScreenBase
std::unique_ptr<PauseScreen> m_pause(new PauseScreen());
std::vector<std::unique_ptr<ScreenBase>*> screens;
screens.push_back(&m_game); // this gets the error
I get compile error:
C2284 “cannot convert parameter 1 from ‘std::unique_ptr<_Ty> *’ to ‘std::unique_ptr<_Ty> *&&’
If I comment out the last line, it compiles fine.
Basically, I would like to have a collection of the derived items (or rather pointers to them). I’ve tried various ways of ‘pointing and/or referencing’ the parameter and various ways of establishing the T in vector<T> but the solution eludes me.
I’m reading a lot of:
I would encourage people to default to
unique_ptrwhen unsure. Plopping downshared_ptrwithout memory ownership design is exactly what leads to cyclic memory leaks.Yes, you can create cyclic memory leaks with
unique_ptrtoo. However my experience has been that whenunique_ptris used it encourages the designer to understand who owns what as the design evolves, making cyclic memory leaks less likely, and easier to debug when they do occur.And if during this design process, the designer discovers that shared ownership semantics is actually needed, then by all means, reach for
shared_ptr(and probablyweak_ptrtoo to break those cycles).Finally, bind your raw pointers to your smart pointers as quickly as possible. The following is a compilable sketch of the OP’s problem which follows best practices: