Mike
Mike

Reputation: 1857

push back a new vector into a vector

I read the following code piece.

vector<vector<int>> result;
//level is an integer. 
if (level > result.size())
     result.push_back(vector<int>());

I'm wondering: What does vector<int>() create, an object or a pointer of vector?

I think it should be a vector object, instead of a pointer of vector. Otherwise, it won't compile.

However, I feel that vector<int>() is similar to new vector<int>() .

Maybe I missed something?

I really appreciate it if you could point out the knowledge point I missed.

Thank you very much!

Upvotes: 0

Views: 140

Answers (1)

user4581301
user4581301

Reputation: 33932

Both cases are similar in that they provide a real, honest-to-god object. The differences are in how you access it and how long it lives.

vector<int>() creates an object in Automatic storage with Automatic storage duration. You can consider this one an object that you can hold in your digital hand, but only temporarily. Without an associated identifier it goes out of scope and vanishes, is destroyed, at the end of the line. Before destruction it is copied into result. With an identifier (eg. vector<int> vec;), an Automatic variable lasts until the identifier reaches the end of its scope.

new vector<int>() creates an object in Dynamic storage with Dynamic storage duration and gives you a pointer to it. This object is out there somewhere and all you "hold" is information about how to find it. Couple problems in this case. You've noticed the first, result will not accept a pointer to a vector. It wants the real thing. The other problem is objects with Dynamic storage duration hang around until they are manually destroyed with delete or the process ends. Unless you have a pointer to it, the memory is lost, floating through space without a tether you can use to access and delete it.

In general, avoid new unless you find one of the rare cases where you cannot avoid it, and in those cases prefer a smart pointer.

Upvotes: 3

Related Questions