为什么调用shared_from_this会调用std :: terminate [英] Why calling shared_from_this calls std::terminate

查看:50
本文介绍了为什么调用shared_from_this会调用std :: terminate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

class A : public std::enable_shared_from_this<A>
{
public:
     std::shared_ptr<A> f()
     {
          return shared_from_this();
     }
};

int main()
{
    A a;
    std::shared_ptr<A> ptr = a.f();
}

此代码在Visual Studio 2017中终止。我想我在这里做错了。谁能帮我这个?我想要一个由shared_from_this()创建的shared_ptr。

This code terminated in Visual Studio 2017. I guess I am doing something wrong here. Can anyone help me with this? I want a shared_ptr on a created by shared_from_this().

推荐答案

因为 a 不是共享指针拥有的。来自 cppreference

Because a is not a owned by a shared pointer. From cppreference:


只允许在以前共享的对象上,即在std :: shared_ptr管理的对象上,调用shared_from_this。否则,该行为是不确定的(直到C ++ 17)(从C ++ 17开始,由默认构造的weak_this的shared_ptr构造函数引发)std :: bad_weak_ptr抛出。

It is permitted to call shared_from_this only on a previously shared object, i.e. on an object managed by std::shared_ptr. Otherwise the behavior is undefined (until C++17)std::bad_weak_ptr is thrown (by the shared_ptr constructor from a default-constructed weak_this) (since C++17).

这篇关于为什么调用shared_from_this会调用std :: terminate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆