简体   繁体   English

在范围内创建新对象并退出时会发生什么

[英]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.

相关问题 如果将变量设置为等于新对象,旧对象会发生什么情况? - What happens to the old object if you set a variable equal to a new object? 使用另一个(现有)对象创建新对象时会发生什么? - What happens when a new object is created using another (existing) object? 通过赋值初始化C ++对象时会发生什么? - What happens when you initialize a C++ object by assignment? 在UNIX中使用_exit时,未清除的资源会发生什么变化? - What happens to the resources that aren't cleaned up when you use _exit in UNIX? 当 QFuture 超出范围时会发生什么? - What happens when QFuture goes out of scope? 如果在宏中声明变量会发生什么? - What happens if you declare a variable inside a macro? 如果你取消引用`new int`会发生什么? - What happens if you dereference `new int`? 如果在其他线程仍在运行时调用exit(0)会发生什么? - What happens if you call exit(0) while other threads are still running? 当我通过引用传递一个对象并且它超出范围时,C ++会发生什么? - What happens in C++ when I pass an object by reference and it goes out of scope? 当您将NSMutable *对象传递给接受NS *对象的方法时,会发生什么? - What happens when you pass a NSMutable* object to a method accepting a NS* object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM