[英]What happens when you create new object inside a scope and exit
If you create an object of any class inside a function and you push it into a vector, when you exit that function what happens to the object? 如果在函数内部创建任何类的对象并将其推入向量中,那么退出该函数时该对象会发生什么? It gets destroyed? 它被摧毁了吗? If yes why? 如果是,为什么? It shouldn't since we have a vector referring that object that will be used later in the code... 不应该这样,因为我们有一个向量引用了该对象,该对象将在以后的代码中使用...
void class::foo(){
//this class object has a private vector called 've'
ve.push_back(aNotherClass(somearg));
//watever
}//exit
void class::foo2(){
aNotherClass an = ve.pop_back(); //example code not sure if it works.
cout << an.getSomeAtrribute() << endl;
//will print like 432042 something like this and I'm sure it is not that value. is it '->' or '.' ?
}
vector.push_back
makes a copy of the argument. vector.push_back
复制该参数。 The local object you created will be destroyed, but the vector will retain a copy. 您创建的本地对象将被销毁,但矢量将保留一个副本。 However, if that copy is just a copy of a pointer then you're in trouble. 但是,如果该副本只是指针的副本,那么您将遇到麻烦。
The local object created on stack (without using the new operator) will be destroyed. 在堆栈上创建的本地对象(不使用new运算符)将被销毁。 It is the language specification. 这是语言规范。
From the other side, the vector can be implemented in a way that it will create its own copy of an object. 另一方面,向量可以以创建对象自己的副本的方式实现。 Thus allowing you to keep the data event after exit from the function. 因此,您可以在退出函数后保留数据事件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.