2017-10-21 250 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