Is an STL container pointer safe?

What if I specify an unique_ptrinstance of an STL container as follows? Is this code safe?

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

Would not it the fact that the destructor to vector<int>be called twice, because both myself vector<int>and unique_ptrtry to clear the memory, you still got vector<int>? Could this lead to undefined behavior? Or does the compiler somehow know that it vector<int>has released its memory and does not call the destructor again for the sake of unique_ptrleaving the scope?

It is easy to understand that if someone was so stupid to do it, could it be dangerous?

+4
source share
1 answer

With unique_ptr< vector<int> > p1( new vector<int> ); unique_ptra call deleteto vector. The destructor will vectorthen free up its allocated memory. So it is safe.

But vector<int>enough. I do not see a case when you want unique_ptr< vector<int> >.

+6
source

Source: https://habr.com/ru/post/1611515/


All Articles