【问题标题】:Deep Copy behaviour of a vector while returning from the function [duplicate]从函数返回时向量的深度复制行为[重复]
【发布时间】:2017-09-25 09:33:30
【问题描述】:

如果有人可以解释为什么当我从函数返回向量深拷贝时它不起作用,这将很有帮助

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

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

【问题讨论】:

标签: c++ c++11 visual-c++ c++14


【解决方案1】:

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

vec 的附加临时副本创建。

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

从 C++17 开始,这是编译器必须实现的。

【讨论】:

    猜你喜欢
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 2015-08-11
    • 1970-01-01
    相关资源
    最近更新 更多