2014-09-02 209 views
1

有人可以解釋爲什麼以下崩潰?我正在使用enable_shared_from_this,以便bob不會被刪除。enable_shared_from_this。爲什麼會崩潰?

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? 
} 
+2

「調用'shared_from_this'之前,應該有至少一個'的std :: shared_ptr的 p'擁有'* this'。」 - [來源](http://en.cppreference.com/w/cpp/memory/enable_shared_from_this/shared_from_this) – clcto 2014-09-02 17:08:32

+0

@clcto,我認爲你的評論值得提升爲答案。 – 2014-09-02 17:17:47

回答

3

documentation狀態:

在致電shared_from_this,應該有至少一個std::shared_ptr<T> p擁有*this

因此,如果我們改變main()到:

std::shared_ptr<Person> bob(new Person ("Bob")); 
bob->introduce(); 

不會有問題,因爲已經有一個shared_ptr擁有*this

+0

或更好: 'std :: shared_ptr bob = std :: make_shared (「Bob」);'' – 2017-08-02 00:34:14

5

一個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(); 
}