复制初始化:为什么即使关闭copy-elision也没有调用移动或复制构造函数?

Han*_*IAO 4 c++ initialization implicit-conversion copy-initialization copy-elision

我的问题不同,因为我可能"知道"复制省略.我正在学习复制初始化.但是,以下代码使我感到困惑,因为我已经使用-fno-elide-contructors -O0选项关闭了copy-elision .

#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;
}
Run Code Online (Sandbox Code Playgroud)

我首先用命令构建: 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
Run Code Online (Sandbox Code Playgroud)

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

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

son*_*yao 7

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

它不应该.test instance = {1,2}复制列表初始化,作为效果,适当的构造函数(即test::test(int, int))用于instance直接构造对象.这里不需要构造临时和调用复制/移动构造函数.