【发布时间】:2015-04-05 00:19:56
【问题描述】:
#include <memory>
#include <iostream>
struct A : public std::enable_shared_from_this<A>
{
~A()
{
auto this_ptr = shared_from_this(); // std::bad_weak_ptr exception here.
std::cout << "this: " << this_ptr;
}
};
int main()
{
auto a = std::make_shared<A>();
a.reset();
return 0;
}
我在调用shared_from_this() 时收到std::bad_weak_ptr 异常。是设计使然吗?是的,这可能很危险,因为在析构函数返回后无法使用此指针,但我看不出为什么在技术上不可能在此处获取指针,因为共享指针对象显然仍然存在并且可以用过的。除了写我自己的enable_shared_from_this 模拟(我宁愿不这样做)之外,有什么办法可以避免这种情况?
【问题讨论】:
-
@Drax:我已经看到了这个问题。它涉及
boost而不是std,答案讨论了相关代码的具体设计,而不是shared_from_this()可用性的主要限制。 -
@VioletGiraffe 这个问题既不涉及
boost也不涉及std,只涉及弱引用的概念。
标签: c++ c++11 destructor shared-ptr weak-ptr