Lets say I have a class node with copy, move constructor, default constructor
Node func (Node n){
return n;
}
Node newN = func(Node{}); //#2
Then how many times are these called?
Move constuctor: once at #2.
What about copy constructor?
At best one construction and one move construction.
#include <iostream>
using std::cout;
using std::endl;
class Something {
public:
Something() {
cout << __PRETTY_FUNCTION__ << endl;
}
Something(Something&&) {
cout << __PRETTY_FUNCTION__ << endl;
}
Something(const Something&) {
cout << __PRETTY_FUNCTION__ << endl;
}
};
Something foo(Something in) {
return in;
}
int main() {
Something something = foo(Something{});
(void) something;
}
The output for the above is this
Something::Something()
Something::Something(Something &&)
The construction of the Something object results in a prvalue, which is a candidate for RVO, this will be elided into the function parameter for foo(). If you compile with C++17 this will be elided no matter what, but when you compile with C++11 and C++14 this will be elided only if elisions are not disallowed with the -fno-elide-constructors compilation flag.
However when you return that object from the function, NRVO isn't allowed to happen by the standard. Eliding from function parameters is explicitly disallowed (see below for the exact quote from the standard). So a move happens (assuming you have a move constructor, if you don't have a move constructor then a copy will take place)
So in total with elisions allowed you have one construction and one move construction (if no move constructor is defined then you get a copy)
§ 15.8.3 Copy/move elision [class.copy.elision]
When certain criteria are met, an implementation is allowed to omit the copy/move construction of a class object, ...
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 parameter or a variable introduced by the exception-declaration of a handler (18.3)) 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 call’s return object
As you can see the language disallows elision from function parameters, so a move happens.
Also note that if you delete the move constructor explicitly, this code will not compile
Related
suppose I have the following code.
std::string foo() {
std::string mystr("SOMELONGVALUE");
return mystr;
}
int main() {
std::string result = foo();
}
When I call 'foo', is the data in mystr copied or moved into result? I believe that it is moved C++11 style, but I was hoping for clarification and/or links to show that.
Thanks!
Edit: I suppose I want to know the answer to this question when compiling with g++ for c++11 or later.
Your example fall on the so-called Named Return Value Optimization, which is defined in this paragraph of the C++11 standard. So the compiler may elide the copy constructor (or move constructor since C++14). This elision is not mandatory.
In C++11, if the compiler does not perform this elision, the returned string will be copy constructed. The returned object would be moved if it were naming a function parameter, [class.copy]/32 (bold is mine):
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. [...]
In C++14, this last rule has changed. It also includes the case of automatic variables [class.copy]/32:
When the criteria for elision of a copy/move operation are met, but not for an exception-declaration, and the object to be copied is designated by an lvalue, or when the expression in a return statement is a (possibly parenthesized) id-expression that names an object with automatic storage duration declared in the body or parameter-declaration-clause of the innermost enclosing function or lambda-expression, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. [...]
So in your example code, and in C++14, if the compiler does not elide the copy/move construction, the returned string will be move constructed.
Like user4581301 said, I suspect copy elision to happen (not a move) in most implementations. For c++11 and c++14, the standard allows copy elision to happen but doesn't mandate it. In c++17, some instances of copy elision will become mandated. So, for c++11 and c++14, technically the answer depends on the implementation being used. In your case specifically, we're talking about a specific type of copy elision: return value optimization (RVO). To check whether RVO happens in your environment for your given case, you can run this code:
#include <iostream>
struct Foo {
Foo() { std::cout << "Constructed" << std::endl; }
Foo(const Foo &) { std::cout << "Copy-constructed" << std::endl; }
Foo(Foo &&) { std::cout << "Move-constructed" << std::endl; }
~Foo() { std::cout << "Destructed" << std::endl; }
};
Foo foo() {
Foo mystr();
return mystr;
}
int main() {
Foo result = foo();
}
My implementation opts for RVO - no move takes place.
Since std::string result = foo(); is an initializer, it will call the constructor rather than the assignment operator. In C++11 or newer, there is guaranteed to be a move constructor with prototype std::basic_string::basic_string( basic_string&& other ) noexcept. On every actually-existing implementation, this moves the contents rather than copying them. Although I don’t believe the standard mandates a particular implementation, it does say this particular operation must run in constant and not linear time, which precludes a deep copy. As the return value of foo() is a temporary rvalue, that is the constructor that will be called in this snippet.
So, yes, this code will move the string rather than copy it.
The expression in a return statement will not always be copied, however. If you return std::string("SOMELONGVALUE"); (a programmatic constructor), the implementation is permitted to construct the result in place instead. If foo() returns a std::string& and returns anything other than a temporary, that will be returned by reference. (Returning a reference to a temporary that's been destroyed is, as you know, undefined behavior!) And some compilers, even before C++11, would perform copy elision and avoid creating a temporary only to copy and destroy it. Newer versions of the Standard make copy elision mandatory in most situations where it’s possible, but compilers were doing it even before that.
The way the most compilers implement return of a class type is to pass an extra "hidden" argument to the function that is a pointer to the memory where the value being returned should be constructed. So the called function can copy or move the return value into that memory as needed without regard to the call site.
With your example code, such a compiler could even use that same memory to hold the mystr variable, constructing it directly there, and never using either the move or copy constructor of std::string.
In my VS2015, the compiler does invoke move ctor when returning an temp variable in such a trivial case.
class A {
public:
A(int _x) :x(_x) {}
A(const A& a) {
cout << "copy ctor." << endl;
x = a.x;
}
A(A&& a) {
cout << "move ctor." << endl;
x = 123;
}
private:
int x;
};
A foo() {
A temp = { 7 };
return temp; //invoke move ctor
}
int main() {
A a = foo();
return 0;
}
Besieds, whether the compiler trigger RVO depends on the
price of copying, you can see the mechanism of RVO in below:
https://www.ibm.com/developerworks/community/blogs/5894415f-be62-4bc0-81c5-3956e82276f3/entry/RVO_V_S_std_move?lang=en
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.
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.
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
if I compile (under G++) and run the following code it prints "Foo::Foo(int)". However after making copy constructor and assignment operators private, it fails to compile with the following error: "error: ‘Foo::Foo(const Foo&)’ is private". How comes it needs a copy constructor if it only calls standard constructor at runtime?
#include <iostream>
using namespace std;
struct Foo {
Foo(int x) {
cout << __PRETTY_FUNCTION__ << endl;
}
Foo(const Foo& f) {
cout << __PRETTY_FUNCTION__ << endl;
}
Foo& operator=(const Foo& f) {
cout << __PRETTY_FUNCTION__ << endl;
return *this;
}
};
int main() {
Foo f = Foo(3);
}
The copy constructor is used here:
Foo f = Foo(3);
This is equivalent to:
Foo f( Foo(3) );
where the first set of parens a re a call to the copy constructor. You can avoid this by saying:
Foo f(3);
Note that the compiler may choose to optimise away the copy constructor call, but the copy constructor must still be available (i.e not private). The C++ Standard specifically allows this optimisation (see section 12.8/15), no matter what an implementation of the copy constructor actually does.
What you see, is a result of allowed by standard optimization, when compiler avoids creation of temporary. Compiler is allowed to replace construction and assignment with simple construction even in presence of side effects (like IO in your example).
But fact if program is ill-formed or not should not depend on situation, when compiler makes this optimization or not. That's why
Foo f = Foo(3);
requires copy constructor. And
Foo f(3);
does not. Though it will probably lead to same binary code.
Quote from 12.8.15
When certain criteria are met, an
implementation is allowed to omit the
copy construction of a class object,
even if the copy constructor and/or
destructor for the object have side
effects. In such cases, the
implementation treats the source and
target of the omitted copy 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.111) This
elision of copy operations 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 with the same
cv-unqualified type as the function
return type, the copy 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 to a
class object with the same
cv-unqualified type, the copy
operation can be omitted by
constructing the temporary object
directly into the target of the
omitted copy
See also "Return value optimization".