gpt4 book ai didi

c++ - shared_from_this 和私有(private)继承

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:28:18 28 4
gpt4 key购买 nike

cpp reference有这个如何使用 std::enable_shared_from_this 的例子(略微调整)

class Good : std::enable_shared_from_this<Good>
{
public: std::shared_ptr<Good> getptr() { return shared_from_this(); }
};

...

auto good = std::make_shared<Good>();
good->getptr();

但是,这在 Visual Studio 2015(企业版,版本 14.0.25123.00 更新 2)中不起作用,即 std::bad_weak_ptr抛出异常。

查看其他示例(包括来自 cpp referenceMicrosoft 的不同示例)我注意到他们使用 public继承而不是 private一。并使用 public继承实际上解决了我的问题(不再是 std::bad_weak_ptr,而是一个有效的 shared_ptr)。

Cpp 引用没有提到我必须公开继承自 std::enable_shared_from_this ,那么错误在哪里呢? Visual Studio 的行为是否错误(我猜想在使用 private 继承时存在可见性问题)或者 cpp 引用没有提及此限制?

附言:make_shared<good>()shared_ptr<Good>(new Good)没有区别。

PSS:两个版本都编译得很好,私有(private)版本就不起作用,这是一种非常讨厌的错误。

编辑:已更改 structclass . Cpp 引用在其示例中实际上使用了public 继承。 仍然没有说它必须公开。它实际上列在那里,我只需要学会仔细阅读。谢谢@Angew。

最佳答案

std::enable_shared_from_this 的典型实现需要 std::shared_ptr 构造函数(在您的情况下由 std::make_shared 调用) 以便能够检测 std::enable_shared_from_this 基的存在,因此它可以设置该基的 std::weak_ptr 成员。

对于私有(private)继承,这是不可能的,因此您会得到调用 shared_from_this 时遇到的运行时异常(因为 std::weak_ptr 从未设置,因为 std::shared_ptr 构造函数无法检测到 std::enable_shared_from_this 基数)。

C++ 标准提到了这样一个实现:

[ Note: A possible implementation is shown below:

template<class T> class enable_shared_from_this {
private:
weak_ptr<T> __weak_this;
protected:
constexpr enable_shared_from_this() : __weak_this() { }
enable_shared_from_this(enable_shared_from_this const &) { }
enable_shared_from_this& operator=(enable_shared_from_this const &) { return *this; }
~enable_shared_from_this() { }
public:
shared_ptr<T> shared_from_this() { return shared_ptr<T>(__weak_this); }
shared_ptr<T const> shared_from_this() const { return shared_ptr<T const>(__weak_this); }
};

The shared_ptr constructors that create unique pointers can detect the presence of an enable_shared_from_this base and assign the newly created shared_ptr to its __weak_this member. — end note ]

cppreference page您链接到的也在注释中提到了这一点。

关于c++ - shared_from_this 和私有(private)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40020154/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com