This program:
#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';
}
when compiled by gcc-4.7.1 outputs (link):
move constructor
copy constructor
move constructor
Why does the comma operator have this effect? The standard says:
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?
A move constructor allows the resources owned by an rvalue object to be moved into an lvalue without creating its copy. An rvalue is an expression that does not have any memory address, and an lvalue is an expression with a memory address.
std::move is actually just a request to move and if the type of the object has not a move constructor/assign-operator defined or generated the move operation will fall back to a copy.
To correct this, remove the move constructor completely. In the case of the class, once a copy constructor is present (user defined), the move is implicitly not generated anyway (move constructor and move assignment operator).
Automatic move is based on eligibility for copy elision:
§12.8 [class.copy] p32
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. [...]
And copy elision in turn is allowed when the return expressions is the name of an automatic object.
§12.8 [class.copy] p31
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With