Consider that TEST code:
#include <iostream>
using namespace std;
class Klass
{
public:
Klass()
{
cout << "Klass()" << endl;
}
Klass(const Klass& right)
{
cout << "Klass(const Klass& right)" << endl;
}
};
Klass create(Klass a)
{
cout << "create(Klass a)" << endl;
return a;
}
int main()
{
const Klass result = create(Klass());
}
Compiling with:
g++ -O3 rvo.cpp -o rvo
The output is:
$ ./rvo
Klass()
create(Klass a)
Klass(const Klass& right)
I was expecting the compiler to use the RVO mechanism in order elide every COPY CTOR call, to avoid copying the return value AND the parameter of the function create(). Why isn't it the case?
The standard allows copy elision only in case where you pass a temporary as a function argument.
The two elisions you're expecting are bolded below:
[C++11: 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. 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 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 by treating the 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. [..]
It didn't happen for the return value because the non-volatile name was a function parameter.
It has happened for the construction into create's parameter, otherwise you'd have seen:
Klass()
Klass(const Klass& right)
create(Klass a)
Klass(const Klass& right)
The copy you see is a copy for the "return" statement in the "create" function. It cannot be eliminated by RVO, as it is not possible to construct the return value directly. You requested to "return a". A copy is needed here; there is no way to return an object without it.
In a standard speak, following condition of [C++11: 12.8/31] is not met
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
As for the reasons, it is not an arbitrary rule, it makes sense from implementation point of view, as this is what is not possible to do with a function parameters:
constructing the automatic object directly into the function’s return value
You are copying the function parameter. You cannot elide this copy without inlining, as the parameter already exists before you enter the function, therefore you cannot construct that object into the return value directly instead.
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).
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.
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