确保c++对象被正确地解分配
Ensuring C++ Object is properly de-allocated
我开始自学c++,如何在没有垃圾收集器的情况下处理对象,这让我感到有些困惑。下面是我要做的一个简单的例子:
A* a;
B b = new B(a); // Note that B is a derived class of A
a = &b;
while (a != NULL)
{
(*a).run();
}
这一切都像我期望的那样工作。我遇到的问题是,在B的run()方法中,我想做这样的事情:
C c = new C(a); // a is the same pointer as above, that has been stored
// and C another derived class from A
a = &c;
然后让run()退出。然后,第一个块中的while循环将在新对象上调用run()。我的问题是,我如何确保原始b的内存被正确地解除分配?
在这种情况下可以使用std::shared_ptr
。如果两个类的成员需要指向同一个对象,那么可以将它们都设置为shared_ptr
。你通常这样做,但是如果在这样做的时候,如果你要创建循环依赖,那么打破这个循环依赖,你需要std::weak_ptr
。
下面是std::shared_ptr
和std::weak_ptr
的例子。
错误代码(循环依赖):
struct B;
struct A
{
std::shared_ptr<B> bp;
}
struct B
{
std::shared_ptr<A> ba; //this creates a cyclic dependency.
}
正确代码(非循环):
struct B;
struct A
{
std::shared_ptr<B> bp;
}
struct B
{
std::weak_ptr<A> ba; //break cyclic dependency with std::weak_ptr
}
当你面对动态内存分配和重要的所有权语义时,智能指针通常是确保正确性的好方法。
参见std::shared_ptr
。
相关文章:
- 如何正确地将分支添加到已存在的树中
- 如何正确地将带有指针的数组传递给函数
- 如何正确地推回然后遍历堆中对象的向量?
- 我是否不正确地集中了这些字符数组?
- 如何通过另一个对象中的命令正确地从一个对象返回数据
- 我怎样才能通过友谊正确地履行我的职能?
- C++:如何正确地将 deque::front() 返回的变量从函数中传递出去?
- 我应该如何正确地将packaged_task移动到 lambda?
- 如何正确地将SHA1CryptoServiceProvider转换为c ++?
- 如何正确地对 constexpr 函数进行单元测试
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- 如何正确地将boost::asio::buffers_iterator转换为InputIterator
- 如何正确地检查变量char中包含的字母
- 当试图交换可变模板类时,如何正确地重载operator=
- 如何正确地将 boost::optional<std::chrono::d uration> 作为函数参数?
- 如何在C++中正确地将我的语言字符输出到HTML文件中
- 我如何正确地为std ::映射分配内存
- 如何正确地在void函数内部动态分配2d数组
- 在c++中正确地重新分配内存
- 确保c++对象被正确地解分配