如果您在函数内创建任何类的对象并将其放入 vector 中,当您退出该函数时该对象会发生什么情况?它被摧毁了?如果是,为什么?它不应该,因为我们有一个引用该对象的 vector ,稍后将在代码中使用...
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
复制参数。您创建的本地对象将被销毁,但 vector 将保留一个拷贝。但是,如果该拷贝只是指针的拷贝,那么您就有麻烦了。
关于c++ - 当您在范围内创建新对象并退出时会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36496926/