想象一下 java 或 C# 中的以下类:
class A
{
B b;
//some other stuff
public A(B b) {this.b = b;}
}
class B
{
A createA() {return new A(this); }
}
然后我们会使用它,例如
A complicatedCreateA()
{
B = new B();
return b.createA();
}
虚拟机/CLR 会确保我们不会泄漏内存。
我如何在 C++ 中实现类似的模式,这样我才不会泄漏内存和引用已清理的资源?
编辑: 为了说得更清楚,我特别担心如果我多次调用 createA() 会发生什么,以及不同的对象 A 何时会有不同的生命周期,例如:
A anotherMethod()
{
B = new B();
A a = b.createA();
//use a locally, or use with yet another object C, etc.
return b.createA();
}
我对智能指针在 C++ 中的工作原理有基本的了解。但是,即使我做了类似的事情:
boost::shared_ptr<B> b(new B());
那么我无法从 B 中访问这个智能指针,所以我不能将它传递给 A。否则 A 怎么才能确保相应的对象 B 既不会太迟也不会太早被删除?
最佳答案
确切的等价物有点复杂:
class A
{
std::shared_ptr<B> b;
//some other stuff
public:
A(std::shared_ptr<B> const & b) : b(b) {}
};
class B : public std::enable_shared_from_this<B>
{
public:
A createA() {return A(shared_from_this());}
};
A complicatedCreateA()
{
std::shared_ptr<B> b = std::make_shared<B>();
return b->createA();
}
或者,您可以通过使 createA
成为非成员(或静态成员,如果它需要访问 B
来避免 shared_from_this
恶意键s privates),采用共享指针参数:
A createA(std::shared_ptr<B> const & b) {return A(b);}
A complicatedCreateA()
{
std::shared_ptr<B> b = std::make_shared<B>();
return createA(b);
}
关于c++ - C++ 中的特定内存管理问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8972296/