I spotted a snippet of C++ code that goes like this:
// constructor that creates a 2D vector _store[nRow][nCol]
FlexiMatrix::FlexiMatrix(int nRow)
{
for (int i = 0; i < nRow; i++){
_store.push_back( vector<int>() );
_store[i].push_back( 0 );
}
}
And _store is declared as follows: vector< vector<int> > _store;
It seems to violate my understanding of local variables and the stack. Shouldn’t the locally created vector’s memory cease to exist the moment we exit this constructor? This is more so given that vector<int>.push_back() requires an alias reference as its input parameter, so the copy constructor is never invoked and what push_back() receives is the actual reference to the local variable?
No.
std::vector_push_back()makes a copy of the passed object. The content of the object passed as parameter might be copied/moved(in C++11) to the newly created object.There are two forms of
push_back()since C++11:In your case,
vector<int>()creates a temporary(r-value)and hence the second form will be used. This second form will move the content of the temporary to the new object which gets added to your vector. Hence, It will use the move constructor & not the copy constructor.