有人可以解释为什么以下崩溃?我正在使用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?
}
Run Code Online (Sandbox Code Playgroud)
其中一个先决条件shared_from_this是object(this)必须已经被某些人拥有shared_ptr.然后它返回一个shared_ptr与已存在的共享所有权shared_ptr.
因为shared_ptr在调用时你的对象不属于任何对象shared_from_this,所以你正在调用未定义的行为(它崩溃).
试试这个:
int main() {
auto bob = std::make_shared<Person>("Bob");
bob->introduce();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1239 次 |
| 最近记录: |