copy elision
copy elision是指编译器为了优化,将不需要的copy操作直接省略了。比如函数返回值的copy操作和构造函数的copy操作等。
例子如下
#include<iostream>
using namespace std;
class A{
public:
A(){
cout<<"default Constructor called"<<endl;
}
A(const A &a){
cout<<"Copy constructor called"<<endl;
}
A& operator=(const A &a) {
cout<<"Assignment operator called"<<endl;
return *this;
}
// explicit A(int a){
// cout<<"Parameterized constructor called"<<endl;
// }
A(int a){
cout<<"Parameterized constructor called"<<endl;
}
};
A foo(){
return A();
}
A bar(){
A a;
return a;
}
int main(){
A a(1);
A b = 1;
A c = foo();
A d = bar();
return 0;
}
copy elision发生在
- a 直接调用值构造函数创建A,省略了copy操作
- b 直接调用值构造函数创建A,省略了copy操作
- c 直接调用默认构造函数创建A,省略了2次copy操作
- d 直接调用默认构造函数创建A,省略了2次copy操作
默认编译选项的输出为
Parameterized constructor called
Parameterized constructor called
default Constructor called
default Constructor called
如果加上-fno-elide-constructors编译选项,输出为
Parameterized constructor called
Parameterized constructor called
Copy constructor called
default Constructor called
Copy constructor called
Copy constructor called
default Constructor called
Copy constructor called
Copy constructor called
在使用copy elision时,初始化=和()效果是一样的,都会只调用构造函数,但=的实际含义是隐式调用值构造函数,然后调用拷贝构造函数,而()的实际含义是直接调用构造函数。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律