我正在學習C++ 11的功能,特別是shared_ptr
,並且我在提及this
時遇到問題,並將其用作其他類的參考。將「this」引用爲shared_ptr?
這樣做的原因是我有一個Simulation
實例被傳遞給模擬中的其他實例(例如Apple
),因此他們可以自己修改模擬,甚至從模擬中刪除自己。
在我的更復雜的代碼中,我得到一個double free
錯誤(當程序存在時),據我瞭解from here我不應該在同一個原始對象上創建兩次shared_ptr
。當模擬類不知道this
已經是shared_ptr
時,我如何將this
作爲shared_ptr
傳遞給Apple
對象?
我的想法是通過在初始化參數的shared_ptr
但這似乎是多餘的,例如:
// The argument is a std::shared_ptr<Simulation>
simulation->initSomethingElse(simulation);
也許我想在一個不尋常的方式來實現這一點,也許我的理解是不完全正確?也許有更好的方法來做到這一點呢?
下面我有一個簡單的例子:
#include <memory>
class Simulation;
class Apple {
public:
void init(std::shared_ptr<Simulation> simulation) {
this->simulation = simulation;
};
private:
std::shared_ptr<Simulation> simulation;
};
class Simulation {
public:
void initSomethingElse() {
auto apple = std::shared_ptr<Apple>(new Apple());
// incorrect second reference to the raw pointer
apple->init(std::shared_ptr<Simulation>(this));
};
};
int main() {
auto simulation = std::shared_ptr<Simulation>(new Simulation());
simulation->initSomethingElse();
return 0;
}
你在哪裏銷燬'shared_ptr'實例? –
Dai
2014-09-25 04:21:54