复制初始化:即使关闭了复制删除功能,为何仍未调用move或copy构造函数? [英] copy initialization : why move or copy constructor was not called even if copy-elision is turned off?

查看:92
本文介绍了复制初始化:即使关闭了复制删除功能,为何仍未调用move或copy构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My question is different because I may "know" copy-elision. I am learning copy initialization. However,the following code confused me because I have already turned off the copy-elision using -fno-elide-contructors -O0 option.

#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,结果如下:

I first build with the command: g++ -std=c++11 -fno-elide-constructors -O0 main.cpp -o main and I got the result as following:

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

然后,我使用不带-fno-elide-constructor -O0选项的命令进行构建,以证明g++确实关闭了我先前构建中的优化.

Then I built with command without -fno-elide-constructor -O0 option to attest that g++ indeed turned off the optimization in my previous build.

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

So, why test instance = {1,2} does not call copy constructor or move constructor? Isn't a temp object created from the implicit conversion? And instance is supposed to be initialized by that temp object?

推荐答案

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

why test instance = {1,2} does not call copy constructor or move constructor?

不应该. test instance = {1,2}复制列表初始化,适当的构造函数(即test::test(int, int))用于直接构造对象instance.无需在此处构造临时结构并调用复制/移动构造函数.

It shouldn't. test instance = {1,2} is copy-list-initialization, as the effect, the appropriate constructor (i.e. test::test(int, int)) is used to construct the object instance directly. No needs to construct a temporary and call copy/move constructor here.

这篇关于复制初始化:即使关闭了复制删除功能,为何仍未调用move或copy构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆