1
这将是有帮助的是有人能解释为什么矢量深拷贝不工作时,我从一个函数返回它深复制行为
我有一个构造函数和拷贝一个struct构造这样
struct {
A() { cout<<"Constructor..."<<endl; }
A(const A &) { cout<<"Copy Constructor...."<<endl;
};
如果我写这样
int main() {
A a1; // constructor gets called here
vector<A> vec;
vec.push_back(a1) // Copy constructor gets called here
vector<A> copyvec = vec; // Again copy constructor gets called here
}
主程序但是,如果我改变这样
代码vector<A> retvecFunc() {
A a1; // Constructor gets called
vector<A> vec;
vec.push_back(a1); // Copy Constructor gets called
return vec; // copy constructor **DOESN'T GETS CALLED**
}
我的主要功能是写成
int main() {
vector<A> retVec = retvecFunc();
return 0;
}
你可能想做一些关于[copy-elision和返回值优化]的研究(http://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization)。 –