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时,初始化=和()效果是一样的,都会只调用构造函数,但=的实际含义是隐式调用值构造函数,然后调用拷贝构造函数,而()的实际含义是直接调用构造函数。

posted @ 2024-02-08 23:33  trashwin  阅读(12)  评论(0编辑  收藏  举报