C++11 move constructor not called, default constructor preferred - c++

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

Related

c++11 copy/move control doesn't work in my supposed way [duplicate]

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

Move Constructor vs Copy Elision. Which one gets called?

I have two pieces of code here to show you. They are two classes and each one provides a Move Constructor and a function which returns a temporary.
In the first case, the function returning a temporary calls the Move Constructor
In the second case, the function returning a temporary just tells the compiler to perform a copy elision
I'm confused: in both cases I define a Move Constructor and a random member function returning a temporary. But the behavior changes, and my question is why.
Note that in the following examples, the operator<< was overloaded in order to print a list (in the first case) and the double data member (in the second case).
MOVE CONSTRUCTOR GETS CALLED
template<typename T>
class GList
{
public:
GList() : il{ nullptr } {}
GList(const T& val) : il{ new Link<T>{ val,nullptr } } {}
GList(const GList<T>& copy) {}
GList(GList<T>&& move)
{
std::cout << "[List] Move constructor called" << std::endl;
// ... code ...
}
// HERE IS THE FUNCTION WHICH RETURNS A TEMPORARY!
GList<T> Reverse()
{
GList<T> result;
if (result.il == nullptr)
return *this;
...
...
...
return result;
}
};
int main()
{
GList<int> mylist(1);
mylist.push_head(0);
cout << mylist.Reverse();
return 0;
}
The output is:
[List] Move constructor called
0
1
COPY ELISION PERFORMED
class Notemplate
{
double d;
public:
Notemplate(double val)
{
d = val;
}
Notemplate(Notemplate&& move)
{
cout << "Move Constructor" << endl;
}
Notemplate(const Notemplate& copy)
{
cout << "Copy" << endl;
}
Notemplate Redouble()
{
Notemplate example{ d*2 };
return example;
}
};
int main()
{
Notemplate my{3.14};
cout << my.Redouble();
return 0;
}
The output is:
6.28
I was expecting a call to the Move Constructor in the second example.
After all, the logic for the function is the same: return a temporary.
Will someone explain me why that's not happening?
How do I deal with copy elisions?
I want my code to be the most portable I can, how can I be sure of these kinds of optimizations by the compiler?
In the comments of another SO answer, the OP clarifies what he is asking here:
I heard that copy elision CAN occur even when there are more than 1
return statements. I'd like to know when a copy elision is forbidden
And so I am attempting to address this issue here:
Elision of copy/move operations (referred to as copy elision by the C++ standard) is permitted in the following circumstances:
In a return statement in a function with a class return type, when the expression is the name of anon-volatile object with automatic storage duration (other than a function parameter or a variable introduced by the exception-declaration of a handler) with the same type (ignoring cv-qualification) 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 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 would be copied/moved to a class object with the same type (ignoring cv-qualification), 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 declares an object of the same type (except for cv-qualification) as the exception object, the copy 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. There cannot be a move from the exception object because it is always an lvalue.
Copy elision is forbidden in all other circumstances.
The number of return statements in a function has no bearing whatsoever on the legality of copy elision. However a compiler is permitted to not perform copy elision, even though it is legal, for any reason at all, including the number of return statements.
C++17 Update
There are now a few places where copy elision is mandatory. If a prvalue can be bound directly to a by-value function parameter, or a by-value return type, or to a named local variable, copy elision is mandatory in C++17. This means that the compiler shall not bother even checking for a copy or move constructor. Legal C++17:
struct X
{
X() = default;
X(const X&) = delete;
X& operator=(const X&) = delete;
};
X
foo(X)
{
return X{};
}
int
main()
{
X x = foo(X{});
}
The copy elision is an optimization that, nowadays, every modern compiler provides.
When returning huge class objects in C++, this technique applies... but not in every case!
In the first example, the compiler performs the Move Constructor because we have more than one return statement in the function.

extra copy on class construction

In C++, when initializing a class like
MyClass(myBigObject s):
s_(s)
{
...
}
it looks as if s is copied once at function entry ("pass by value") and once when being assigned to s_.
Are compilers smart enough to strip out the first copy?
Compilers are allowed to strip out the first copy iff
The copy does not have observable behavior according to the as-if rule.
For this rule to apply, your compiler must know neither constructor nor destructor of myBigObject have any observable side-effects when compiling the user of the MyClass ctor.
1.9 Program Execution
The semantic descriptions in this International Standard define a parameterized nondeterministic abstract
machine. This International Standard places no requirement on the structure of conforming implementations.
In particular, they need not copy or emulate the structure of the abstract machine. Rather, conforming
implementations are required to emulate (only) the observable behavior of the abstract machine as explained
below.
or if they can use the copy-elision rule, which allows disregarding the as-if rule.
For this to apply, you must feed the constructor an anonymous unbound object.
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 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):
— 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
— 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.
Far easier to take the argument by movable-reference &&, which allows replacing the second copy with a move under any circumstances.
First copy into s can be omitted for a temporary
An optimizing compiler will likely omit the first copy if you pass a temporary object:
MyClass x{ myBigObject() };
This is likely to invoke the copy constructor only once since the temporary myBigObject will be constructed directly into the constructor argument s.
Note that this can change the observable behaviour of your program.
#include <iostream>
struct myBigObject
{
size_t x;
myBigObject() : x() {}
myBigObject(myBigObject && other)
{
std::cout << "Move myBigObject" << std::endl;
}
myBigObject(const myBigObject &other)
{
std::cout << "Copy myBigObject" << std::endl;
x = 12;
}
};
struct MyClass
{
MyClass(myBigObject s)
: s_(s)
{
std::cout << "x of s : " << s.x << std::endl;
std::cout << "x of s_ : " << s_.x << std::endl;
}
myBigObject s_;
};
int main()
{
std::cout << "A:" << std::endl;
MyClass x{ myBigObject() };
std::cout << "B:" << std::endl;
myBigObject y;
MyClass z{ y };
}
It prints (https://ideone.com/hMEv1W + MSVS2013,Toolsetv120)
A:
Copy myBigObject
x of s : 0
x of s_ : 12
B:
Copy myBigObject
Copy myBigObject
x of s : 12
x of s_ : 12
Second copy into s_ cannot be elided
The copy into s_ cannot be omitted since s and s_ need to be different objects.
If you want only one copy of myBigObject in your class you can go for:
MyClass(myBigObject const & s)
: s_(s)
{
}
MyClass(myBigObject && s)
: s_(std::forward<myBigObject>(s))
{
}
This way you do not see any copies in case of the temporary and only one copy for non-temporary objects.
The altered code will print:
A:
Move myBigObject
B:
Copy myBigObject
compiler cannot optimize copying from argument to calss field in general case. Apparently your object can have complex copy constructor with side effects that cannot be omited.
But in your case you probably want to replace copying with moving.
You should write move constructor and use std::move to move s to _s:
myBigObject(myBigObject&&other);
MyClass(myBigObject s):
s_(std::move(s))
{
...
}
In that case code like
MyClass obj((myBigObject()));
will end up with zero copyings as object will be first moved to constructor and then to class field.

Why Copy constructor is NOT called to copy the temporary object to the new defined object

#include <iostream>
using namespace std;
class Y {
public:
Y(int ) {
cout << "Y(int)\n";
}
Y(const Y&) {
cout << " Y(const Y&)\n";
}
};
int main() {
Y obj1 = 2; // Line 1
}
Output: Y(int)
Expected Output: Y(int)
Y(const Y&)
Question> Based on my understanding, Line 1 will first create a temporary object Y(2), and then assign the temporary object to obj1. Thus, I expect both Y(int) and Y(const Y&) are called. But the output from vs2010 only reports the first one(i.e. Y(int)). Why?
Why?
Because under certain conditions (specified by paragraph 12.8/31 of the C++11 Standard) calls to the copy constructor or move constructor can be elided even though those special functions (or the destructor) 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
— [...]
This is the only exception to the so-called "as-if" rule, which normally constrains the kind of transformations (optimizations) that a compiler can perform on a program in order to preserve its observable behavior.
Notice, that the above mechanism is called copy elision - even when it's actually a call to the move constructor that is being elided.
This is because the constructor has only one parameter and it's not marked explicit, so the compiler automatically turns:
Y obj1 = 2;
Into:
Y obj1(2);
To prevent this behaviour, use:
explicit Y(int ) {
cout << "Y(int)\n";
}
(and compilation will fail in your case).
This is called copy initialization. Y(int ) is a conversion constructor. that is
single-parameter constructor that is declared without the function
specifier explicit
the compiler is allowed to elide the extra copy and use your conversion constructor. Which means
Y obj1 = 2; // Line 1
is equivalent to
Y obj1(2); // Line 1

Why the copy constructor is not called?

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.