在c++中,如何編寫析構函數來釋放指向結構的指針的內存?

[英]In C++, how to write a destructor for freeing memory of pointer to a structure?


Here's my structure A

這是我的一個結構

struct A {
    int a1;
    int a2;
    ~A() { }
};

B is another structure that contains a pointer to A

B是另一個包含指向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?

我需要刪除/釋放ptrB指向的所有內存。因此,我需要在結構b中編寫正確的析構函數。如何遍歷和刪除每個元素?

3 个解决方案

#1


12  

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.

如果使用的是c++ 11編譯器,只需使用std::shared_ptr,就不用擔心刪除。這是因為shared_ptr是一個“智能”指針,它將自動刪除其指向的內容。

#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++ 11編譯器,就可以從BOOST庫獲得共享指針。

#2


6  

You need only to delete objects allocated by new. In this case there's no need to delete b1 as it has not been dynamically-allocated. Moreover, if you did not initialize ptr2a with dynamic memory, deleting it is undefined behavior.

您只需要刪除新分配的對象。在這種情況下,不需要刪除b1,因為它還沒有動態分配。此外,如果沒有使用動態內存初始化ptr2a,刪除它是未定義的行為。

So there's no need to worry about deleting As data as it will be destructed from memory along wih the instance of the class.

因此,不需要擔心將數據作為數據刪除,因為它將沿着類的實例從內存中被銷毀。

#3


4  

You've only got one pointer to A. So you only need to delete that:

你只有一個指向a的指針,所以你只需要刪除它:

~B() {
     delete ptr2A;
}

Note that you can't delete b1, since it's a plain int! (The memory taken up by the variables of the structure, such as b1 and the pointer ptr2A itself (not what it points to) are destroyed automatically along with any instances of that structure.)

注意不能刪除b1,因為它是一個普通的int類型!(由結構的變量,如b1和指針ptr2A本身(不是它指向的內容)所占用的內存,會隨該結構的任何實例自動銷毀。)


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/02/21/d61f99eb7f5fe2757457383b04dd776d.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com