Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deallocation of a vector in C++ [duplicate]

Tags:

c++

stl

vector

Possible Duplicate:
deleting dynamically allocated object that contains vector in C++ STL

I have a struct like this

struct foo {
  vector<int> myvector;
};

Now, I create a pointer to foo, resize and insert some elements into the vector.

foo *myfoo = new foo;
myfoo->myvector.resize(100);
myfoo->myvector.push_back(0);
myfoo->myvector.push_back(1);
... // and so on

Now, before myfoo goes out of scope, I would have to deallocate the memory allocated to it with

delete myfoo;

My question is whether this would take care freeing myvector also? I have this particular query because now that myvector is resized, the STL library would presumably allocated the container in the heap. So, when I free up myfoo, I wouldn't want the memory allocated to myvector leaking.

like image 918
borncrusader Avatar asked Jan 30 '26 15:01

borncrusader


1 Answers

Yes, deleting myfoo will destroy all of its members too, which includes the std::vector. It's important to note that if you had pointers inside foo, only the pointers would be destroyed, not the objects they point to (unless of course you defined a destructor that did that job for you - which you should!).

It is mandated by the standard that after execution of the destructor, any non-static data members are destroyed also (§12.4/8):

After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X's direct non-variant non-static data members, the destructors for X’s direct base classes and, if X is the type of the most derived class (12.6.2), its destructor calls the destructors for X's virtual base classes.

The class foo has a defaulted destructor because no user-declared destructor is defined (§12.4/4):

If a class has no user-declared destructor, a destructor is implicitly declared as defaulted (8.4).

The destructor of myfoo is called when it is deleted (§5.3.5/6):

If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will invoke the destructor (if any) for the object or the elements of the array being deleted.

A delete-expression is an expression of the form:

::opt delete cast-expression

like image 70
Joseph Mansfield Avatar answered Feb 02 '26 05:02

Joseph Mansfield



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!