Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 复制初始化:为什么即使关闭了复制省略,也没有调用move或copy构造函数?_C++_Initialization_Implicit Conversion_Copy Elision_Copy Initialization - Fatal编程技术网

C++ 复制初始化:为什么即使关闭了复制省略,也没有调用move或copy构造函数?

C++ 复制初始化:为什么即使关闭了复制省略,也没有调用move或copy构造函数?,c++,initialization,implicit-conversion,copy-elision,copy-initialization,C++,Initialization,Implicit Conversion,Copy Elision,Copy Initialization,我的问题是不同的,因为我可能“知道”复制省略。我正在学习复制初始化。但是,以下代码让我感到困惑,因为我已经使用-fno elide constructors-O0选项关闭了复制省略 #include <iostream> using namespace std; class test{ public : test(int a_, int b_) : a{a_}, b{b_} {} test(const test& other) { co

我的问题是不同的,因为我可能“知道”复制省略。我正在学习复制初始化。但是,以下代码让我感到困惑,因为我已经使用
-fno elide constructors-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;
}
然后,我使用命令构建,而不使用
-fno elide构造函数-O0
选项,以证明
g++
确实在我以前的构建中关闭了优化

那么,为什么
testinstance={1,2}
不调用复制构造函数或移动构造函数呢?不是通过隐式转换创建临时对象吗?而
实例
应该由该临时对象初始化吗

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


不应该
testinstance={1,2}
实际上是使用适当的构造函数(即
test::test(int,int)
)直接构造对象
实例。无需构造临时构造函数并在此处调用复制/移动构造函数。

确定。我在这里补充一些资料。 :

<> >代码> t对象= {其他} /CODE实际上是复制初始化,直到C++ 11,它将其视为列表初始化。

顺便说一句,如果构造函数是显式的,调用将失败

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