gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:28:22 24 4
gpt4 key购买 nike

有人可以解释为什么以下崩溃吗?我正在使用 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/

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