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。我提供你的幫助。
A的構造函數使用make_shared創建新的A對象,它涉及調用A的構造函數...... - 無限循環。 – navyblue
@navyblue本來是一個答案......我想這對你來說是一個微不足道的問題。謝謝 – user7865286
在筆記上...你可能會對'std :: shared_from_this'感興趣# – pqnet