2

I'm trying to understand rvalue reference. This is the code I've written so far:

class A {
public:
    A(const char* str) {
        std::cout << str;
    }

    A(A&& other) {
        std::cout << "other";
    }
};

int main() {
    A m(A(A(A("hello"))));
}

The output is only "hello", which makes me confused.

Since A("hello") is a temporary object passed to the second constructor, But the code output is as if only the first constructor is called.

I guess either this is a compiler optimization or i miss some details about constructors and rvalues.

Casey
  • 10,297
  • 11
  • 59
  • 88
ariaman5
  • 132
  • 1
  • 8

2 Answers2

3

What you observe is also known as copy elision, more precisely:

Under the following circumstances, the compilers are required to omit the copy and move construction of class objects, even if the copy/move constructor and the destructor have observable side-effects. The objects are constructed directly into the storage where they would otherwise be copied/moved to. The copy/move constructors need not be present or accessible:

(...)

  • In the initialization of an object, when the initializer expression is a prvalue of the same class type (ignoring cv-qualification) as the variable type:

T x = T(T(f())); // only one call to default constructor of T, to initialize x

which is exactly your case.

Note that the optimization is mandatory for C++17 onwards. It is optional for C++11, but it seems that your compiler applies it anyway.

freakish
  • 54,167
  • 9
  • 132
  • 169
2

Yes this is a compiler/language(see latter) optimization.

As can be seen here, this will output:

hello

Changing the standard from -std=c++2a to -std=c++14 in the compiler options will still give you hello only, but in addition to the standard change if you also add: -fno-elide-constructors to the options you should see what you're hoping for.

However, this option will no longer work if you specify C++17 or C++2a as standard as this elision has become mandatory in certain situations since those standards, your situation is one of those.

Hatted Rooster
  • 35,759
  • 6
  • 62
  • 122