Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Delete a struct?

I have a struct that contains pointers:

struct foo
{
    char* f;
    int* d;
    wchar* m;
}

I have a vector of shared pointers to these structs:

vector<shared_ptr<foo>> vec;

vec is allocated on the stack. When it passes out of scope at the end of the method, its destructor will be called. (Right?) That will in turn call the destructor of each element in the vector. (Right?) Does calling delete foo delete just the pointers such as foo.f, or does it actually free the memory from the heap?

like image 759
Nick Heiner Avatar asked Jun 08 '10 21:06

Nick Heiner


2 Answers

delete foo;

will delete the memory allocated to the foo structure, which includes the three pointers. But the memory pointed to by the pointers themselves will only be deleted if you implement a destructor that explicitly deletes them.

like image 190
bshields Avatar answered Sep 22 '22 08:09

bshields


If you have dynamically allocated foo, e.g.:

foo* f = new foo;

then delete f will destroy the dynamically allocated foo object including the pointers it contains but not anything pointed to by the pointers, if they do indeed point at dynamically allocated objects or arrays of objects.

If you've assigned a dynamically allocated foo object (i.e. the result of new foo) to a shared_ptr (assuming tr1 or boost) then when the last shared_ptr referring to that object goes out of scope delete will be called on the pointer originally returned by new foo automatically. You don't have to do this manually.

If your object (foo) contains pointers to dynamically allocated objects that it owns (so need deallocating at the end of the lifetime of the foo), then it's highly recommended that you write a destructor to deallocate these objects in the correct way (which will depend on how they are allocated).

Once you've written a destructor you need to consider whether you need to write a copy constructor and copy-assingment operator. As you are using a vector of shared pointers you may decide that your objects should not be copied. If so you can declare these as private and need not provide an implementation.

You should also consider one or more constructors to ensure that your pointer members are initialized. If the pointer members are never initialized then if they are not assigned to during the lifetime of a foo then they will neither be null, nor point to a valid object and this is likely to cause an error in your destructor.

like image 43
CB Bailey Avatar answered Sep 20 '22 08:09

CB Bailey