In this code:
#include <iostream>
using std::cout;
class Foo {
public:
Foo(): egg(0) {}
Foo(const Foo& other): egg(1) {}
int egg;
};
Foo bar() {
Foo baz;
baz.egg = 3;
return baz;
}
int main(void) {
Foo spam(bar());
cout << spam.egg;
return 0;
}
the output is 3, while I expected it to be 1.
That means the copy constructor is not called in the line Foo spam(bar()).
I guess it's because the bar function doesn't return a reference.
Could you please explain what's really going on at the initialization of spam?
I apologize in advance if that's a dumb question.
Thanks!
Copy/move elision is the only allowed exception to the so-called "as-if" rule, which normally constrains the kinds of transformations (e.g. optimizations) that a compiler is allowed to perform on a program.
The rule is intended to allow compilers to perform any optimization they wish as long as the transformed program would work "as if" it was the original one. However, there is one important exception.
Per paragraph 12.8/31 of the C++11 Standard:
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class
object, even if the constructor selected for the copy/move operation and/or the destructor for the object
have side effects. [...] This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which
may be combined to eliminate multiple copies):
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
[...]
when a temporary class object that has not been bound to a reference (12.2) would be copied/moved
to a class object with the same cv-unqualified type, the copy/move operation can be omitted by
constructing the temporary object directly into the target of the omitted copy/move
[...]
In other words, you should never rely on a copy constructor or move constructor being called or not being called in the cases for which the provisions of 12.8/31 apply.
Related
In the following example I am expecting only a single copy-construction, as I thought the intermediate copies would by copy elided. The only required (I thought?) copy would be in the constructor of B to initialize the member variable a.
#include <iostream>
struct A
{
A() = default;
A(A const&) { std::cout << "copying \n"; }
};
struct B
{
B(A _a) : a(_a) {}
A a;
};
struct C : B
{
C(A _a) : B(_a) {}
};
int main()
{
A a{};
C c(a);
}
When I execute this code (with -O3) I see the following output
copying
copying
copying
Why aren't these intermediate copies elided?
Here are the cases, where copy elision is allowed (class.copy/31):
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
in a throw-expression, when the operand is the name of a non-volatile automatic object (other than
a function or catch-clause parameter) whose scope does not extend beyond the end of the innermost
enclosing try-block (if there is one), the copy/move operation from the operand to the exception
object (15.1) can be omitted by constructing the automatic object directly into the exception object
when a temporary class object that has not been bound to a reference (12.2) would be copied/moved
to a class object with the same cv-unqualified type, the copy/move operation can be omitted by
constructing the temporary object directly into the target of the omitted copy/move
when the exception-declaration of an exception handler (Clause 15) declares an object of the same type
(except for cv-qualification) as the exception object (15.1), the copy/move operation can be omitted
None of these are true for your example (we are not in a return statement, throw-expression or exception-declaration. And there are no temporaries in your example at all.), so copy happens each time you expect to happen.
Note, that copy elision is allowed in the mentioned cases, but not mandatory. So even, for these cases, the compiler is allowed to emit copies (this is true for C++11. In C++17, there are some cases, where copy elision is mandatory. But, none of your example cases allows elision in C++17 either.)
Expanding on the discussion under the other answer, the copy here has side effects (printing to console), and so does not qualify for copy optimization.
Copy elision, however, is allowed regardless of side effects, per the cppreference article on copy elision. It's not allowed here because you have lvalues all the way. None of the copies you hoped to eliminate were of an rvalue or prvalue. To make them an rvalue, you need to cast using std::move or construct them as nameless temporaries as part of the constructor call.
Again, the cppreference article explains it much better.
You are passing the a object to the C constructor by value. And then it is being passed to the B constructor by value.
Suppose we have this class:
class X {
public:
explicit X (char* c) { cout<<"ctor"<<endl; init(c); };
X (X& lv) { cout<<"copy"<<endl; init(lv.c_); };
X (X&& rv) { cout<<"move"<<endl; c_ = rv.c_; rv.c_ = nullptr; };
const char* c() { return c_; };
private:
void init(char *c) { c_ = new char[strlen(c)+1]; strcpy(c_, c); };
char* c_;
};
and this sample usage:
X x("test");
cout << x.c() << endl;
X y(x);
cout << y.c() << endl;
X z( X("test") );
cout << z.c() << endl;
The output is:
ctor
test
copy
test
ctor <-- why not move?
test
I am using VS2010 with default settings. I'd expect the last object (z) to be move-constructed, but it's not! If I use X z( move(X("test")) ); then the last lines of the output are ctor move test, as I'd expect. Is it a case of (N)RVO?
Q: Should the move-ctor be called according to the standard? If so, why isn't it called?
What you are seeing is copy elision, which allows the compiler to directly construct a temporary into a target it is to be copied/moved into and thus elide a copy (or move) constructor/destructor pair. The situations in which the compiler is allowed to apply copy elision are specified in §12.8.32 of the C++11 standard:
When certain criteria are met, an implementation is allowed to omit
the copy/move construction of a class object, even if the copy/move
constructor and/or destructor for the object have side effects. In such
cases, the implementation treats the source and target of the omitted
copy/move operation as simply two different ways of referring to the
same object, and the destruction of that object occurs at the later of
the times when the two objects would have been destroyed without the
optimization. This elision of copy/move
operations, called copy elision, is permitted in the following
circumstances (which maybe combined to eliminate multiple copies):
in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object 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
in a throw-expression, when the operand is the name of a non-volatile automatic object whose scope does not extend beyond
the end of the innermost enclosing try-block (if there is one), the
copy/move operation from the operand to the exception object (15.1)
can be omitted by constructing the automatic object directly into
the exception object
when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with he
same cv-unqualified type, the copy/move operation can be omitted by
constructing the temporary object directly into the target of the
omitted copy/move
when the exception-declaration of an exception handler (Clause 15) declares an object of the same type (except for cv-qualification) as
the exception object (15.1), the copy/move operation can be omitted
bytreatingthe exception-declaration as an alias for the exception
object if the meaning of the program will be unchanged except for the
execution of constructors and destructors for the object declared by
the exception-declaration.
The ctor output you get in your third code line is for the construction of the temporary object. After that, indeed, the temporary is moved into the new variable z. In such a situation the compiler may choose to elide the copy/move, and it seems that is what it did.
The Standard states:
(§12.8/31) When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects. [...] This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
[...]
- when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move
[...]
One important condition is that the source object and the destination are of the same type (apart from cv-qualification, i.e. things like const).
Therefore, one way you can force the move constructor to be called is to combine the object initialization with implicit type conversion:
#include <iostream>
struct B
{};
struct A
{
A() {}
A(A&& a) {
std::cout << "move" << std::endl;
}
A(B&& b) {
std::cout << "move from B" << std::endl;
}
};
int main()
{
A a1 = A(); // move elided
A a2 = B(); // move not elided because of type conversion
return 0;
}
You are calling X's char* constructor X("test") explicitly.
Therefore it is printing ctor
The title basically says it all:
Where does the C++14 standard specify initialization of function arguments and initialization from function return values?
As an aside: To align what my compiled program does and what the C++ standard says in regards to initialization, I use the --no-elide-constructors argument to gcc. This argument keeps GCC from eliding (i.e. optimizing) superfluous constructor calls. I.e.
#include <iostream>
#define CALLED std::cout << __PRETTY_FUNCTION__ << " called" << std::endl
class C {
public:
C() { CALLED; }
C(const C &c) { CALLED; }
C(const C &&c) { CALLED; }
};
C f() { return C(); }
int main()
{
C c = f();
return 0;
}
gives with c++ -std=c++14:
C::C() called
and with c++ --no-elide-constructors -std=c++14:
C::C() called
C::C(const C&&) called
C::C(const C&&) called
It seems your primary objective is to find the specification of copy elision. That's in 12.8 [class.copy] paragraph 31, first (for the return) and third (for passing argument) bullet
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the constructor selected for the copy/move operation and/or the destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization. This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
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 cvunqualified 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
...
when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move
Other than that the specification on how the arguments and return are built involves pretty much the entire chapter on expressions...
I found what I was searching for in 5.2.2 [expr.call] (4) (for initialization of function arguments) and 6.6.3 [stmt.return] (2) (for return values).
So, code first:
#include <iostream>
#include <utility>
struct X{
int i;
void transform(){}
X() :i(0){std::cout<<"default\n";}
X(const X& src): i(src.i){std::cout<<"copy\n";}
X(X&& msrc) :i(msrc.i){msrc.i=0;std::cout<<"move\n";}
};
X getTransform(const X& src){
X tx(src);
tx.transform();
return tx;
}
int main(){
X x1;// default
X x2(x1); // copy
X x3{std::move(X{})}; // default then move
X x41(getTransform(x2)); // copy in function ,then what?
X x42(std::move(getTransform(x2))); // copy in funciton, then move
X x51( (X()) );//default, then move? or copy?
// extra() for the most vexing problem
X x52(std::move(X())); //default then move
std::cout<<&x41<<"\t"<<&x51<<std::endl;
}
Then ouput from cygwin + gcc 4.8.2 with C++11 features turned on:
default
copy
default
move
copy
copy
move
default
default
move
0x22aa70 0x22aa50
What I don't quite get is the line for x41 and x51. For x41, should the temporary returned from the function call invoke the move constructor or the copy? Same question for x51.
A second question is that, by looking at the output, the constructions of x41 and x51 didn't call any constructors defined, but the objects are clearly created as they reside in memory. How could this be?
An unnamed object matches && better than const&, naturally.
Otherwise move semantics would not work.
Now, there are fewer calls to your default/copy/move-constructors, then one might naively expect, because there's a special rule allowing the ellision of copies, without regard to observable behavior (which must otherwise be preserved by optimizations):
12.8 Copying and moving of objects § 31
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects. In such cases, the implementation treats the source and target of the omitted copy/move operation as simply two different ways of referring to the same object, and the destruction of that object occurs at the later of the times when the two objects would have been destroyed without the optimization.123 This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
Still, if it is returned from a function and directly used to initialize an object of the same type, that move will be omitted.
— 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.
— when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move.
- [... 2 more for exception handling]
So, going through your list:
X x1;// default
// That's right
X x2(x1); // copy
// Dito
X x3{std::move(X{})}; // default then move
// Yes. Sometimes it does not pay to call `std::move`
X x41(getTransform(x2)); // copy in function ,then what?
// Copy in function, copy to output, move-construction to x41.
// RVO applies => no copy to output, and no dtor call for auto variable in function
// Copy ellision applies => no move-construction nor dtor of temporary in main
// So, only one time copy-ctor left
X x42(std::move(getTransform(x2))); // copy in funciton, then move
// `std::`move` is bad again
X x51( (X()) );//default, then move? or copy? // extra() for the most vexing problem
// Copy-elision applies: default+move+dtor of temporary
// will be optimized to just default
X x52(std::move(X())); //default then move
// And again `std::`move` is a pessimization
I thought using static_cast might avoid binding the temporary, meaning the move can be ellided, but no such luck: 1376. static_cast of temporary to rvalue reference Thanks #dyp for unearthing this issue.
According to the standard § 12.8 [Copying and moving class objects]
31 When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class
object, even if the constructor selected for the copy/move operation and/or the destructor for the object
have side effects. In such cases, the implementation treats the source and target of the omitted copy/move
operation as simply two different ways of referring to the same object, and the destruction of that object
occurs at the later of the times when the two objects would have been destroyed without the optimization.124
This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which
may be combined to eliminate multiple copies)
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 cvunqualified
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.
when a temporary class object that has not been bound to a reference (12.2) would be copied/moved
to a class object with the same cv-unqualified type, the copy/move operation can be omitted by
constructing the temporary object directly into the target of the omitted copy/move
Thus in the both cases (i.e., x41, x51 respectively) you are experiencing a copy elision optimization effect.
I think it's simply Return Value Optimization kicking in. You create a copy within the functions on X tx(src);, and then this local variable is just given back to the main. Semantically as a copy, but in fact the copy operation is omitted.
As others have said, moves can also be omitted.
Suppose we have this class:
class X {
public:
explicit X (char* c) { cout<<"ctor"<<endl; init(c); };
X (X& lv) { cout<<"copy"<<endl; init(lv.c_); };
X (X&& rv) { cout<<"move"<<endl; c_ = rv.c_; rv.c_ = nullptr; };
const char* c() { return c_; };
private:
void init(char *c) { c_ = new char[strlen(c)+1]; strcpy(c_, c); };
char* c_;
};
and this sample usage:
X x("test");
cout << x.c() << endl;
X y(x);
cout << y.c() << endl;
X z( X("test") );
cout << z.c() << endl;
The output is:
ctor
test
copy
test
ctor <-- why not move?
test
I am using VS2010 with default settings. I'd expect the last object (z) to be move-constructed, but it's not! If I use X z( move(X("test")) ); then the last lines of the output are ctor move test, as I'd expect. Is it a case of (N)RVO?
Q: Should the move-ctor be called according to the standard? If so, why isn't it called?
What you are seeing is copy elision, which allows the compiler to directly construct a temporary into a target it is to be copied/moved into and thus elide a copy (or move) constructor/destructor pair. The situations in which the compiler is allowed to apply copy elision are specified in §12.8.32 of the C++11 standard:
When certain criteria are met, an implementation is allowed to omit
the copy/move construction of a class object, even if the copy/move
constructor and/or destructor for the object have side effects. In such
cases, the implementation treats the source and target of the omitted
copy/move operation as simply two different ways of referring to the
same object, and the destruction of that object occurs at the later of
the times when the two objects would have been destroyed without the
optimization. This elision of copy/move
operations, called copy elision, is permitted in the following
circumstances (which maybe combined to eliminate multiple copies):
in a return statement in a function with a class return type, when the expression is the name of a non-volatile automatic object 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
in a throw-expression, when the operand is the name of a non-volatile automatic object whose scope does not extend beyond
the end of the innermost enclosing try-block (if there is one), the
copy/move operation from the operand to the exception object (15.1)
can be omitted by constructing the automatic object directly into
the exception object
when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with he
same cv-unqualified type, the copy/move operation can be omitted by
constructing the temporary object directly into the target of the
omitted copy/move
when the exception-declaration of an exception handler (Clause 15) declares an object of the same type (except for cv-qualification) as
the exception object (15.1), the copy/move operation can be omitted
bytreatingthe exception-declaration as an alias for the exception
object if the meaning of the program will be unchanged except for the
execution of constructors and destructors for the object declared by
the exception-declaration.
The ctor output you get in your third code line is for the construction of the temporary object. After that, indeed, the temporary is moved into the new variable z. In such a situation the compiler may choose to elide the copy/move, and it seems that is what it did.
The Standard states:
(§12.8/31) When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, even if the copy/move constructor and/or destructor for the object have side effects. [...] This elision of copy/move operations, called copy elision, is permitted in the following circumstances (which may be combined to eliminate multiple copies):
[...]
- when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move
[...]
One important condition is that the source object and the destination are of the same type (apart from cv-qualification, i.e. things like const).
Therefore, one way you can force the move constructor to be called is to combine the object initialization with implicit type conversion:
#include <iostream>
struct B
{};
struct A
{
A() {}
A(A&& a) {
std::cout << "move" << std::endl;
}
A(B&& b) {
std::cout << "move from B" << std::endl;
}
};
int main()
{
A a1 = A(); // move elided
A a2 = B(); // move not elided because of type conversion
return 0;
}
You are calling X's char* constructor X("test") explicitly.
Therefore it is printing ctor