移动由逗号运算符压缩的构造函数 [英] Move constructor suppressed by comma operator

查看:109
本文介绍了移动由逗号运算符压缩的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此计划:

#include <iostream>
struct T {
    T() {}
    T(const T &) { std::cout << "copy constructor "; }
    T(T &&) { std::cout << "move constructor "; }
};
int main() {
    ([](T t) -> T { return t; })({}); std::cout << '\n';
    ([](T t) -> T { return void(), t; })({}); std::cout << '\n';
    ([](T t) -> T { return void(), std::move(t); })({}); std::cout << '\n';
}



当您通过gcc-4.7.1输出( link ):

move constructor 
copy constructor 
move constructor 

为什么逗号运算符有此效果?标准说:

Why does the comma operator have this effect? The standard says:


5.18逗号运算子[expr.comma]



1 - [...]类型
和结果的值是右操作数的类型和值;结果与其右操作数[...]具有相同的值类别。如果右操作数的值是一个临时的,结果是临时的。

5.18 Comma operator [expr.comma]

1 - [...] The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand [...]. If the value of the right operand is a temporary, the result is that temporary.

我错过了一些允许逗号运算符

Have I missed something that allows the comma operator to affect the semantics of the program, or is this a bug in gcc?

推荐答案

自动移动是基于复制elision的资格:

Automatic move is based on eligibility for copy elision:

§12.8[class.copy] p32

当满足复制操作的精度的标准满足或者满足时,除了源对象是函数参数,并且要复制的对象由lvalue指定的事实,重载分辨率选择用于复制的构造函数首先被执行,好像对象是由右值指定的。 [...]

When the criteria for elision of a copy operation are met or would be met save for the fact that the source object is a function parameter, and the object to be copied is designated by an lvalue, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. [...]

当返回表达式是自动对象的名称时, / em>。

And copy elision in turn is allowed when the return expressions is the name of an automatic object.

§12.8[class.copy] p31


< - 具有与函数返回类型相同的cv非限定类型的非易失性自动对象(函数或catch子句参数除外),可以通过将自动对象直接构造为函数的返回值来省略复制/移动操作

in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv-unqualified type as the function return type, the copy/move operation can be omitted by constructing the automatic object directly into the function’s return value

插入逗号操作符后,表达式不再是自动对象的名称,而是只有一个引用抑制复制缺陷。

With the comma operator inserted, the expression is not the name of an automatic object anymore, but only a reference to one, which suppresses copy elision.

这篇关于移动由逗号运算符压缩的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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