26

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?

emesx
  • 12,555
  • 10
  • 58
  • 91
  • 2
    It's copy elision. If copy elision failed, then a move would happen. Why does your post title say "default constructor preferred"? No default constructor is being called, and nothing is being preferred in place of the move constructor. It is being eliminated entirely. – Benjamin Lindley Oct 27 '12 at 11:13
  • This code should fail to compile since C++11; a string literal cannot be implicitly converted to non-const `char *`. – M.M Feb 21 '17 at 12:48
  • Possible duplicate of [What are copy elision and return value optimization?](https://stackoverflow.com/questions/12953127/what-are-copy-elision-and-return-value-optimization) – underscore_d Apr 17 '18 at 10:26
  • if you are using g++ then pass flag `-fno-elide-constructors `, this will turn off the copy elision and your move ctor will be invoked – Nilesh Kumar Sep 16 '20 at 16:17

4 Answers4

32

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.
Grizzly
  • 19,595
  • 4
  • 60
  • 78
  • 1
    Can you provide a simple example not using `std::move` that'd force the compiler to use the move constructor? – emesx Oct 27 '12 at 11:17
  • @elmes: Why would you want the move constructor to be called, when it is unnecessary to do so? – Grizzly Oct 27 '12 at 11:19
  • I'd like to see any example of using it with the `X` class, just to believe that there is sense in defining one. – emesx Oct 27 '12 at 11:23
  • 2
    @elmes: `X z((rand() % 2) ? X("test") : X("TEST"));` – Benjamin Lindley Oct 27 '12 at 11:26
  • @elmes: Remember that while copy elision is allowed by the standard, it is not mandated. So there is no guarantee that you'll actually get copy elision, particulary in more complex cases. The typical example is something like the code mentioned by Benjamin Lindley, where ypu have a function/expression, which can return different objects depending on a runtime parameter. Besides a move constructor is useful even if it would only ever be called when the object is explicitely moved, because standard containers/algorithms will use it if possible (and if the move constructor is noexcept). – Grizzly Oct 27 '12 at 11:34
  • 1
    @Grizzly: C++11 demands that when copy-elision *would* be possible (you return a same-type object from a function), every `return local_var;` will first try to move `local_var`. No need for explicit moves, which would hamper (N)RVO. – Xeo Oct 27 '12 at 11:36
  • 2
    @Xeo: I don't follow. The standard might allow copy elision even in the described cases, however whether the compiler can do it, exspecially if the lifetimes overlap, is questionable. And where did I say that an explicit move would ever be needed (or desierable) when returning a local variable? – Grizzly Oct 27 '12 at 11:42
3

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;
}
jogojapan
  • 68,383
  • 11
  • 101
  • 131
  • 1
    Can `A::A(B&& b)` be considered as _move constructor_? N3936 draft (12.8.3) says: "A non-template constructor for class X is a move constructor if its first parameter is of type X&&, const X&&, volatile X&&, or const volatile X&&, and either there are no other parameters or else all other parameters have default arguments" – Bojan Komazec Jul 01 '17 at 17:39
0

You are calling X's char* constructor X("test") explicitly.

Therefore it is printing ctor

Anirudha
  • 32,393
  • 7
  • 68
  • 89
0

Just wanted to comment that if you only want to make sure the move ctor works, you can hack the code to eliminate the compiler optimization by throwing in a condition, for example:

X z( some_val > 1 ? X("test") : X("other test"));
Israel Unterman
  • 13,158
  • 4
  • 28
  • 35