Tongcheng
Tongcheng

Reputation: 17

In C++, when is destructor called automatically for local vector?

For example, say I have the following code:

vector<vector<int>> big;
for (int i=0;i<3;++i){
    vector<int> small;
    small.push_back(3*i+1);
    small.push_back(3*i+2);
    small.push_back(3*i+3);
    big.push_back(small);
}
for (vector<int> s:big){
    for (int a:s){cout<<a<<" ";}
    cout<<endl;
}

The cout gives result that big contains the value for vector small in each for loop, I am confused because I thought the vector small will be destructed automatically in each for loop. Why does the big still have access to the correct value?

Thanks!

Upvotes: 0

Views: 128

Answers (3)

R Sahu
R Sahu

Reputation: 206667

When you execute:

big.push_back(small);

a copy of small is added to big. You can verify that they are two different objects by executing the following:

std::cout << (void*)&big.back() << std::endl;  // big.back() returns a reference to the copy.
std::cout << (void*)&small << std::endl;

You can also verify that they hold the data of the vectors independently. You can print the pointers that hold the data.

std::cout << (void*)big.back().data() << std::endl;
std::cout << (void*)small.data() << std::endl;

Upvotes: 5

Dean Seo
Dean Seo

Reputation: 5693

std::vector<T>::push_back() is copy-based. It creates a copy of the argument, which in this case is small, and stores it in big.

So you're NOT seeing the elements from small, but from big actually.

Upvotes: 1

m7mdbadawy
m7mdbadawy

Reputation: 920

That is because you used big.push_back(small); which made a copy of small vector and when small vector was destroyed at the end of the loop the copy was not effected

Upvotes: 1

Related Questions