在 C++ 中,如何编写析构函数来释放指向结构的指针的内存? [英] In C++, how to write a destructor for freeing memory of pointer to a structure?
问题描述
这是我的结构A
struct A {国际a1;国际a2;~A() { }};
B
是另一个包含指向 A 的指针的结构
struct B {B(int b, A* a): b1(b), ptr2A(a){}国际b1;A* ptr2A;~B() {删除b1;//遍历 A 指向的每个元素,删除它们 <----}};
稍后我使用下面的代码
int bb1;向量<A*>aa1;//做一些事情B *ptrB = 新 B(bb1, aa1);
我需要删除/释放 ptrB 指向的所有内存.因此,我需要在 struct B 中编写正确的析构函数.如何遍历 A 指向的每个元素并删除它们?
如果您使用的是 C++11 编译器,只需使用 std::shared_ptr,您就不必担心删除.这是因为 shared_ptr 是一个智能"指针,它会自动删除它所指向的内容.
#include 结构体B{国际b1;std::shared_ptrptr2A;B(int b, std::shared_ptr a):b1(b),ptr2A(a)({}~B(){}//你看!没有删除!};
每当你分配一些东西时使用共享指针:
#include...{....std::shared_ptrptrB( 新 B(bb1, aa1) );//这是另一种更易读的方法来做同样的事情://auto ptrB = std::make_shared(bb1,aa1);...}//这里没有内存泄漏,因为B被自动销毁
我还应该提到,如果您没有 C++11 编译器,您可以从 BOOST 库.
Here's my structure A
struct A {
int a1;
int a2;
~A() { }
};
B
is another structure that contains a pointer to A
struct B {
B(int b, A* a)
: b1(b), ptr2A(a)
{}
int b1;
A* ptr2A;
~B() {
delete b1;
// traverse each element pointed to by A, delete them <----
}
};
Later on I use below code
int bb1;
vector <A*> aa1;
// do some stuff
B *ptrB = new B(bb1, aa1);
I need to delete/free all the memory pointed to by ptrB. Hence I need to write correct destructor inside struct B. How do I traverse each element pointed to by A and delete them?
If you're using a C++11 compiler, just use std::shared_ptr and you don't have to worry about deletes. This is because the shared_ptr is a "smart" pointer that will automatically delete what its pointing to.
#include <memory>
struct B
{
int b1;
std::shared_ptr<A> ptr2A;
B(int b, std::shared_ptr<A> a):b1(b),ptr2A(a)({}
~B(){} //look ma! no deletes!
};
Use a shared pointer whenever you allocate something:
#include<memory>
...
{
....
std::shared_ptr<B> ptrB( new B(bb1, aa1) );
//Here is another, more readable way of doing the same thing:
//auto ptrB = std::make_shared<B>(bb1,aa1);
...
}
//no memory leaks here, because B is automatically destroyed
Here's more info on the subject of smart pointers.
I should also mention that if you don't have a C++11 compiler, you can get shared pointers from the BOOST library.
这篇关于在 C++ 中,如何编写析构函数来释放指向结构的指针的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!