用元组复制省略

问题描述

我一直有一个错误的印象,如果我在一个返回元组函数中创建临时变量,并在返回语句中使用std::forward_as_tuple,那么就没有副本,就像非元组返回的自动复制省略一样类型。

那我们怎样才能避免复制呢?例如,在以下代码中,func1 在构造时将值 1 和 2 “复制”到 temp 中,并且在返回时没有额外的副本。另一方面,func2 执行相同的构造,但在 return 语句中创建元组时额外复制。

我试着机智一点,并声明临时返回一个元组并在适当的位置构造一个My_struct,如下所示:std::tuple<My_struct> temp {{1,2}}。但是复制构造函数仍然被调用。就我所见,添加移动构造函数无济于事,因为数据成员是简单类型。

#include <iostream>
#include <tuple>

struct My_struct {
    int x,y;
    My_struct(int x,int y) :
      x(x),y(y)
    {
        std::cout << "Constructor called\n";
    }
    My_struct(const My_struct &a) :
      x(a.x),y(a.y)
    {
        std::cout << "copy constructor called!\n";
    }
};

My_struct func1()
{
    My_struct temp {1,2};
    return temp;
}

std::tuple<My_struct> func2()
{
    My_struct temp {1,2};
    return std::forward_as_tuple(temp);
}

int main()
{
    std::cout << "# Calling func1\n";
    auto result1 = func1();

    std::cout << "# Calling func2\n";
    auto result2 = func2();
}

结果:

# Calling func1
Constructor called
# Calling func2
Constructor called
copy constructor called!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)