2017-10-21 253 views
1

我必須在以下代碼中誤解某些內容。我嘗試,並不能明白爲什麼make_shared不能在構造函數被調用,其中在initialize(),它工作正常構造函數不能使用make_shared <T>()

class A { 
public: 
    A() { 
     here = make_shared<A>(); 
    } 
    void initialize(){ 
//  here = make_shared<A>(); 
     cout << &*here << endl; 
     cout << &here << endl; 
    } 
    void hereAddress() { 
     cout << &*here << endl; 
    } 
private: 
    shared_ptr<A> here; 
}; 

int main(){ 
    vector<shared_ptr<A> > myA; 
    cout << "hi" << endl; 
    for (int i = 0; i < 10 ; ++i) { 
     myA.push_back(make_shared<A>()); 
    } 

    for (const auto& i : myA) { 
     i->initialize(); 
     i->hereAddress(); 
    } 
    return 0; 
} 

當我跑,我得到退出碼-1。我提供你的幫助。

+8

A的構造函數使用make_shared創建新的A對象,它涉及調用A的構造函數...... - 無限循環。 – navyblue

+0

@navyblue本來是一個答案......我想這對你來說是一個微不足道的問題。謝謝 – user7865286

+0

在筆記上...你可能會對'std :: shared_from_this'感興趣# – pqnet

回答

0

這是因爲here = make_shared();被調用類的構造函數 ,把它的內部構造將遞歸調用構造器,導致段故障 我們需要把它外面的構造,以避免編譯器抱怨。

+1

編譯器可能不會抱怨這個問題。當你嘗試運行它時,程序更可能會變得很糟糕。 – aschepler