从功能返回时,向量的深拷贝行为
Deep Copy behaviour of a vector while returning from the function
这将有用的是,有人可以解释为什么当我从函数返回时,矢量深拷贝不起作用
我有一个带有构造函数和复制构造函数的结构
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中,这是编译器实现的强制性。
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 与浅拷贝构造函数和深拷贝构造函数混淆
- 如何将深拷贝构造函数实现到链表中?
- 在函数中传递带有指针成员的结构是浅拷贝或深拷贝在 C 中
- C++ 标准::字符串意外更改。我认为这个问题是关于深和浅拷贝的
- 如何正确制作抽象类的深拷贝?
- 从功能返回时,向量的深拷贝行为
- 使用函子或lambda的矢量深拷贝
- STD向量C++ - 深拷贝或浅拷贝
- c++浅/深拷贝
- 懒惰复制-如何从浅拷贝创建深拷贝
- QVector::replace()创建深拷贝吗?
- multi_array_view没有深拷贝的作业
- 如何做深拷贝