<分区>
我正在学习 C++11 特性,特别是 shared_ptr
,我在引用 this
并将其用作其他类的引用时遇到问题.
这样做的原因是我有一个 Simulation
实例,该实例被传递给模拟中的其他实例(例如 Apple
),因此它们可以自己修改模拟,甚至将自己从模拟中移除。
在我更复杂的代码中,我得到了一个 double free
错误(当程序存在时),据我所知 from here我不应该在同一个原始对象上创建两次 shared_ptr
。当模拟类不知道 this
时,如何将 this
作为 shared_ptr
传递给 Apple
对象已经是 shared_ptr
了吗?
我的想法是在初始化参数中传递 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;
}