从功能返回时,向量的深拷贝行为

Deep Copy behaviour of a vector while returning from the function

本文关键字:深拷贝 向量 功能 返回      更新时间:2023-10-16

这将有用的是,有人可以解释为什么当我从函数返回时,矢量深拷贝不起作用

我有一个带有构造函数和复制构造函数的结构

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;
}

它是编译器实现 *命名返回值优化的。

vec的附加临时副本是不是创建的。

即使有副作用(例如,在您的情况下不打印控制台消息),也允许编译器执行此操作。

在C 17中,这是编译器实现的强制性。