The Vivandiere
The Vivandiere

Reputation: 3191

Is a pointer to a STL container safe?

What if I make a unique_ptr point to an instance of an STL container as follows? Is this code safe?

unique_ptr< vector<int> > p1( new vector<int> );

Wouldn't this result in the destructor for the vector<int> being called twice, since both the vector<int> itself and the unique_ptr both attempt to clean up the memory the vector<int> had acquired so far? Could this result in undefined behavior? Or does the compiler somehow knows that that vector<int> has released its memory and does not invoke the destructor again for the sake of the unique_ptr going out of scope?

This is simply to understand that if someone was stupid enough to do this, could it be dangerous?

Upvotes: 5

Views: 923

Answers (1)

Jarod42
Jarod42

Reputation: 217275

With unique_ptr< vector<int> > p1( new vector<int> ); the unique_ptr with call delete on the vector. The destructor of vector will then release its own allocated memory. So it is safe.

But vector<int> is enough. I don't see a case where you'd want unique_ptr< vector<int> >.

Upvotes: 6

Related Questions