[英]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;
}
team
in the member
class, in order to avoid the dangling references problem.member
类中对team
的引用,以避免悬空引用问题。 I think I could use std::shared_ptr and std::weak_ptr.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.只要您正确保护对
team
访问,就可以了。
Changing reference to std::shared_ptr
/ std::weak_ptr
would be problematic.更改对
std::shared_ptr
/ std::weak_ptr
引用会有问题。 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.您将需要在
team
某种initialize()
函数,该函数将在其构造函数之后手动调用并在member
分配弱指针。 This is because shared_from_this()
cannot be used inside constructor.这是因为
shared_from_this()
不能在构造函数中使用。
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
.在这种情况下,
team
和member
似乎是通过组合关系连接起来的,即member
只能存在于一个team
。 In such a design, reference member is fine.在这样的设计中,参考构件很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.