【发布时间】:2015-06-15 18:36:53
【问题描述】:
这样的代码是个好主意: 有什么陷阱吗? 使用共享这个指针是不是更好的设计?
class X {
public:
void foo();
void bar2(const boost::weak_ptr<X>& x);
};
void X::foo() {}
void X::bar2(const boost::weak_ptr<X>& x) {}
void foo()
{
const boost::shared_ptr<X> x = boost::make_shared<X>();
boost::weak_ptr<X> weakX(x);
x->bar2(weakX);
}
int
main()
{
foo();
return 0;
}
【问题讨论】:
-
代码正确(可能有设计问题,未透露)
-
明显的缺陷是这个指针是一个常规指针,因此您可能会遇到在成员函数运行时对象被破坏的情况,请小心。您可能想看看 std::/boost:: enable_shared_from_this。同样的陷阱。