有时我们会遇见这样一个问题:
void func2(shared_ptr<Good>)
struct Good {
void func1() {
//在这里我想要调用func2.
}
}
shared_ptr<Good> a(make_shared<Good>());
a.func1();
如代码中所见,在Good类的成员函数中,我们想要调用一个自己的shared_ptr对象,这是该怎么办呢?
struct Good {
void func1() {
func2(this);
}
}
这样是不可以的,这相当于用同一个指针创建了两个shared_ptr,会导致两次析构而出现错误。
正确的做法是:
struct Good : std::enable_shared_from_this<Good> {
void func1() {
func2(shared_from_this());
}
}
在写smpHttp这个项目时,我将每个Connection放入std::vector<std::shared_ptr<Connection>> 类型的connectionList中,而我在后续调用Connection的成员函数后需要将Connection从connectionList中移除,用到了enable_shared_from_this。特此纪录。