c++ - 启用_shared_from_this。为什么崩溃?

标签 c++ shared-ptr

有人可以解释为什么以下崩溃吗?我正在使用 enable_shared_from_this 这样 bob 就不会被删除。

class Person : public std::enable_shared_from_this<Person> {
    private:
        std::string name;
    public:
        Person (const std::string& name) : name(name) {}
        std::string getName() const {return name;}
        void introduce() const;
};

void displayName (std::shared_ptr<const Person> person) {
    std::cout << "Name is " << person->getName() << "." << std::endl;
}

void Person::introduce() const {
    displayName (this->shared_from_this());
}

int main() {
    Person* bob = new Person ("Bob");
    bob->introduce();  // Crash here.  Why?
}

最佳答案

shared_from_this 的先决条件之一是对象 (this) 必须已经为某个 shared_ptr 所有。然后它返回一个 shared_ptr,它与已经存在的 shared_ptr 共享所有权。

因为在调用 shared_from_this 时您的对象不属于任何 shared_ptr,您正在调用未定义的行为(它崩溃)。

试试这个:

int main() {
    auto bob = std::make_shared<Person>("Bob");
    bob->introduce();
}

关于c++ - 启用_shared_from_this。为什么崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25628704/

相关文章:

c++ - 如何编写混合 C 和 C++ 的 makefile

c++ - shared_ptr 和线程问题

c++ - 识别 C++ 必要包含的快速方法

c++ - 在 endl 上使用带有重载 << 运算符的 ofstream* 包装类

c++ - std::shared_ptr _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) 改变指针时

c++ - 带有模板的 shared_ptr

c++ - boost 的 shared_ptr(shared_ptr<Y> const & r, T * p) 是做什么用的?

c++ - 有一个 weak_ptr 的 vector ,想要返回一个 shared_ptr 的 vector

c++ - for 循环的多操作更改部分中 (void) 的用途

c++ - 如何检测整个周期的C++随机引擎已经被消耗