gpt4 book ai didi

c++ - 从函数返回时 vector 的深度复制行为

转载 作者:行者123 更新时间:2023-11-30 02:23:11 25 4
gpt4 key购买 nike

<分区>

如果有人能解释为什么当我从函数返回时 vector 深度复制不起作用

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com