首页 > 解决方案 > 复制初始化:为什么即使关闭复制省略也不调用移动或复制构造函数?

问题描述

我的问题不同,因为我可能“知道”复制省略。我正在学习复制初始化。但是,下面的代码让我很困惑,因为我已经关闭了复制省略使用-fno-elide-contructors -O0选项。

#include <iostream>
using namespace std;
class test{
public :
    test(int a_, int b_) : a{a_}, b{b_} {}
    test(const test& other)
    {
        cout << "copy constructor" << endl;
    }
    test& operator=(const test& other)
    {
        cout << "copy assignment" << endl;
        return *this;
    }
    test(test&& other)
    {
        cout << "move constructor" << endl;
    }
    test& operator=(test&& other)
    {
        cout <<"move assignment" << endl;
        return *this;
    }

private :
    int a;
    int b;
};

test show_elide_constructors()
{
    return test{1,2};
}

int main()
{
    cout << "**show elide constructors**" <<endl;
    show_elide_constructors();
    cout << "**what is this?**" <<endl;
    test instance = {1,2};//why neither move constructor nor copy constructor is not called?
    cout << "**show move assignment**" <<endl;
    instance = {3,4};
    return 0;
}

我首先使用命令构建: g++ -std=c++11 -fno-elide-constructors -O0 main.cpp -o main我得到的结果如下:

**show elide constructors**
move constructor
**what is this?**
**show move assignment**
move assignment

然后我用没有-fno-elide-constructor -O0选项的命令进行构建,以证明g++确实关闭了我之前构建中的优化。

那么,为什么test instance = {1,2}不调用复制构造函数或移动构造函数呢?不是从隐式转换创建的临时对象吗?并且instance应该由那个临时对象初始化?

标签: c++initializationimplicit-conversioncopy-elisioncopy-initialization

解决方案


为什么test instance = {1,2}不调用复制构造函数或移动构造函数?

它不应该。test instance = {1,2}copy-list-initialization,作为效果,使用适当的构造函数(ie test::test(int, int))直接构造对象instance。无需在此处构造临时并调用复制/移动构造函数。


推荐阅读