I was looking to understand how vector
is implemented in C++. There was a previous question that asked this, and so I took a look at it, and I have a small question. Assuming the implementation in the linked question is correct, let's look at this code:
int main(){
Vector<int> test2 = test_Vector();
cout << test2[0] << endl;
return 0;
}
// below is NOT the STL vector object, but the one in the linked question,
// in which the asker tries to implement STL vector himself/herself
Vector<int> test_Vector(){
Vector<int> test;
test.push_back(5);
return test;
}
As I understand it, the test
Vector
object is created locally, so when the test_Vector
method returns, the local object goes out of scope, thereby calling the destructor and delete
-ing the dynamic array. Since the code actually works and 5 is printed, I guess I'm wrong. What's the right explanation?