gpt4 book ai didi

c++ - 自包含从 std::enable_shared_from_this 继承的自身的 shared_ptr

转载 作者:行者123 更新时间:2023-11-27 23:57:16 25 4
gpt4 key购买 nike

这个问题是这里问题的后续问题:original question

我有一个继承自 std::enable_shared_from_this 的类这个类包含一个std::shared_ptr<Self>

在我知道该类的详细信息完整且成功后,在该类的任何构造函数中,我如何着手分配存储的 std::shared_ptr<Self>成为shared this的那个?

例子:

class Self : public std::enable_shared_from_this<Self> {
private:
std::shared_ptr<Self> me_; // Or
std::unique_ptr>Self> me_;

public:
Self ( /*some parameters*/ );
};

Self::Self( /* some parameters */ ) {
// Check parameters for creation

// Some work or initialization being done

// If all is successful and construction of this class is about
// to leave scope, then set the smart pointer to the this*

// How to do ...
me_ = std::enable_shared_from_this<Self>::shared_from_this();
// Properly if this is even possible at all.
}

最佳答案

你不能。那时,指向当前 Self 实例的 shared_ptr 还不存在。在构造函数返回之前,它不可能存在。 shared_from_this() 有一个前提条件,即指向 thisshared_ptr 已经存在。

关于c++ - 自包含从 std::enable_shared_from_this 继承的自身的 shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41683709/

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