我正在使用shared_ptr<Base>
爲某種具有派生類的樹列表。但是當我的樹遭到破壞時,我得到一個指針違規。C++ shared_ptr <Base>指針訪問衝突
我的代碼看起來是這樣的,再說,這其實similates我運行時錯誤:
#include <iostream>
#include <memory>
#include <vector>
class Base;
typedef std::shared_ptr<Base> pBase;
class Derived;
class Base {
public:
std::vector<pBase> children;
pBase parent;
Base() {}
virtual ~Base() {}
virtual void doSomething() {}
void add(pBase i);
};
class Derived : public Base {
void doSomething() {
// Do something...
}
};
void Base::add(pBase i) {
i->parent = pBase(this);
children.push_back(i);
}
int main() {
pBase tree = pBase(new Derived());
pBase child(new Derived());
child->add(pBase(new Derived()));
tree->add(child);
}
此外,當我下面的行添加到Base::~Base
: 的std ::法院< < 「破壞」 < <名< < std :: endl;
然後在Base
中實現一個名爲name的std :: string,這對每個實例都是不同的,我可以看到析構函數被多次調用(因爲我認爲是Base::parent
引用)。這當然引發了我的錯誤,但我仍然不明白爲什麼會發生這種情況,因爲shared_ptr<Base>
預計會在實際銷燬它之前計算其參考值!!
我希望有人能告訴我我做錯了什麼! 但更重要的是,我該如何解決這個問題!
你沒有初始化'tree',您有其他問題... – ybungalobill
我@ybungalobill很抱歉,我不能看到你闖民宅什麼太? – Tim
因爲你在我指出它之後修復了它...... – ybungalobill