简体   繁体   中英

Question about keeping a reference to a unique_ptr in another class

Recently, I decided that it was time that I should dig into smart pointers. I read about the different kinds (unique, shared, weak), but I'm not sure about one thing.

Let say that I have a class Player and a GameMap class. The content of those classes are irrelevant for the next part. I also have an Engine class, that represents the object that will hold the main components of my game, like this:

class Engine {
public:
    Engine();
    ~Engine();
private:
    std::unique_ptr<Player> m_player;
    std::unique_ptr>GameMap> m_gamemap;
};

These are the only instances of the player and game map that will be created, and the Engine owns them, and should be responsible for their allocation and deletion. So, a unique_ptr seems to be the good choice here.

Now, I would like to keep a simple reference to m_player in my GameMap class, since it would be easier for me than passing the m_player to each function that need it.

My question is: is using a raw pointer (obtained through the get() method) in the GameMap class the best way to keep a reference to the original unique_ptr located in the Engine class? I think that I can't use another unique_ptr pointing to the original one, since it would not be logical regarding to the use case of unique_ptr .

I think that using of raw pointer isn't the best way. For example, better way is use shared_ptr for player and gamemap. And adds weak_ptr of player into gamemap.

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