为什么 std::shared_ptr 的别名构造函数不初始化 std::enabled_shared_from_this?
Why doesn't aliasing constructor of std::shared_ptr initialize std::enabled_shared_from_this?
请考虑以下代码:
struct Foo : std::enable_shared_from_this<Foo>
{
};
struct Bar
{
Foo foo;
};
int main()
{
std::shared_ptr<Bar> bar_p(new Bar);
//make shared_ptr to member with aliasing constructor
std::shared_ptr<Foo> foo_p(bar_p, &bar_p->foo);
assert(bar_p->foo.shared_from_this()); //fail! throws bad_weak_ptr
}
不幸的是,它没有按预期工作(至少在 GCC 4.8.2 中)。我研究了代码,似乎别名构造函数根本不调用__enable_shared_from_this_helper()
这是shared_from_this()
正常工作所必需的。
有人知道为什么它被设计成这样吗?从shared_from_this将shared_ptr退还给会员有什么问题吗?
[util.smartptr.shared.const]
template<class Y> shared_ptr(const shared_ptr<Y>& r, T* p) noexcept;
效果:构造一个
shared_ptr
实例,用于存储p
并与r
共享所有权。
当您调用别名构造函数时,foo_p
不拥有bar_p->foo
,在这种情况下这是一件非常好的事情,否则它会尝试在销毁时delete
它。
[util.smartptr.enab]
shared_ptr<T> shared_from_this();
shared_ptr<T const> shared_from_this() const;
要求: [...]至少应有一个
shared_ptr
实例 p 拥有&t
。
由于bar_p->foo
不属于至少一个人,shared_ptr
你最终会得到未定义的行为,gcc 会抛出bad_weak_ptr
但它没有义务做任何有用的事情。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- std::condition_variable::wait()如何评估给定的谓词
- 如何获取std::result_of函数的返回类型
- std::原子加载和存储都需要吗
- 将对象移动到std::shared_ptr
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 引用 std::shared:ptr 以避免引用计数
- boost::shared_ptr和std::shared-ptr的同居
- 我可以用std::shared_ptr而不是boost::shared-ptr构建boost库吗
- std::dynamic_pointer_cast从基到派生的std::shared返回NULL
- QSharedPointer VS std::tr1::shared_ptr VS boost::tr1::shared