简体   繁体   中英

Replace references storage with std::shared_ptr and std::weak_ptr

I have a simple case where I know things can go wrong if I start to use threads. Godbolt here

#include <iostream>
#include <memory>

class team;

class member
{
    public:
    member(team& my_team) : my_team(my_team) {
        std::cout << "ctor" << std::endl;
    }

    ~member(){
        std::cout << "dtor" << std::endl;
    }

    void modify_my_team()
    {
        //here I want to make sure team is still a valid reference
    }

    private:
    team& my_team;
};

class team
{
    member m1{*this};
    member m2{*this};
    member m3{*this};
};

int main()
{
    team t;
    return 0;
}
  1. In this example, I want to remove the reference to team in the member class, in order to avoid the dangling references problem. I think I could use std::shared_ptr and std::weak_ptr. What's the safest way to do this?
  2. Is it always bad to store a reference?

This example won't break if you add threads (well, no more than any other solution). As long as you protect access to team correctly, it will be fine.

Changing reference to std::shared_ptr / std::weak_ptr would be problematic. You will need some sort of initialize() function in team , which will be called manually after its constructor and assigns the weak pointers in member s. This is because shared_from_this() cannot be used inside constructor.

Using reference as member is not always bad, but some people will frown upon it. In general, as long as you can make sure the reference is valid for the whole lifetime of class, it is safe.
In this case, it seems that team and member are connected with composition relation , ie member can only exist within a team . In such a design, reference member is fine.

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