我希望了解C++中如何实现
据我理解,
vector
。以前有一个相关的问题(链接),我看了一下,有一个小问题。假设链接提问中的实现是正确的,请看这段代码: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;
}
据我理解,
test
Vector
对象是在本地创建的,所以当 test_Vector
方法返回时,局部对象超出范围,从而调用析构函数并 delete
动态数组。既然代码实际上可以运行并打印出 5,那我猜我的理解是错误的。正确的解释是什么?