[英]how to deallocate memory in C++
I have a class A where I construct an object of class B named bb. 我有一个A类,在其中构造了一个名为bb的B类对象。 After constructing the object bb, I run in to a exception in Class A code which is caught by an exception handler.
构造对象bb之后,我遇到了A类代码中的异常,该异常被异常处理程序捕获。 Now my question is how to deallocate the memory of object B in the exception handler?
现在我的问题是如何在异常处理程序中释放对象B的内存?
Use shared_ptr
使用
shared_ptr
struct B {...};
struct A {
A() : bb(new B) {} // auto-deallocate
boost::shared_ptr<B> bb;
}
If the class B object is the member object of class A(aggregate pattern), then you don't even need deallocate it explicitly as long as B itself is RAII-ed. 如果B类对象是A类(聚合模式)的成员对象,那么只要B本身是RAII版本,您甚至不需要显式地分配它。 On the other hand, if it's a heap object( A dynamically allocates bb on heap), you need explicitly release it.
另一方面,如果它是一个堆对象(A在堆上动态分配bb),则需要显式释放它。 You can either use boost::scoped_ptr or boost::shared_ptr(depending on whether you want bb's ownship to be shared with others) to hold the ownship of object bb so that it'll get released automatically when class A object is deleted.
您可以使用boost :: scoped_ptr或boost :: shared_ptr(取决于您是否要与其他人共享bb的所有权)来持有对象bb的所有权,以便在删除A类对象时将其自动释放。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.