Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Operator With Vectors

These questions are relatively straight forward. When using vectors, should I use the new operator when pushing back a new element? And which release method should I call? Here's what I mean:

// Release method: 1.
void ReleaseMethodOne( vector< int * > &ThisVector )
{
    // Clear out the vector.
    ThisVector.clear( );
    return;
}

// Release method: 2.
void ReleaseMethodTwo( vector< int * > &ThisVector )
{
    // Clear out the vector.
    for( unsigned uIndex( 0 ); uIndex < ThisVector.size( ); uIndex++ )
    {
        delete ThisVector.at( uIndex );
    }
    return;
}

int main( )
{
    vector< int * > Vector;

    // Add a new element.
    Vector.push_back( new int( 2 ) );

    // More code...

    // Free the elements before exiting. Which method should I call here?
    ReleaseMethodOne( Vector ); // This one?
    ReleaseMethodTwo( Vector ); // Or this one?

    return 0;
}

I've started learning vectors not long ago and the book I was learning from said that the vector's clear( ) method called each of the elements destructor. Do this apply to the new operator?

like image 208
DeadCapacitor Avatar asked Dec 07 '22 23:12

DeadCapacitor


2 Answers

STL containers store copies of the objects you give to them, pointers in your example. They never release any memory you explicitly allocated. You have to deallocate that memory yourself, so the second "release" method should be used.

Of course, you don't need to new every int. Just use vector<int> instead - you won't have to deal with manual memory management at all.

like image 125
Nikolai Fetissov Avatar answered Dec 09 '22 11:12

Nikolai Fetissov


The clear method will indeed call destructors. However, your vector is storing pointers, and the destructor for pointers is a trivial no-op. It does not call delete.

Therefore, simply calling clear will not free the memory for all the int objects you allocated with new. You need to delete them.

If you use a smart pointer instead of an ordinary pointer, then the pointed-at objects will get freed at the appropriate time without you having to do anything special.

like image 44
Rob Kennedy Avatar answered Dec 09 '22 11:12

Rob Kennedy