0

Here C() is a temporary object which should have been created with no-arg constructor and then I expected a call to move constructor. Yet none of them happened. Can someone exmplain why?

#include <iostream>

using namespace std;
class C{
    public:
        C(){std::cout<<"No arg\n";}
        C(const C& r){std:cout<<"Copy Cons\n";}
        C(C&& r){std:cout<<"Move Cons\n";}
};

int main() {
    C c(C());
}

1 Answers1

3

The statement C c(C()); is actually a function declaration for a function called c that returns C and takes a function (unnamed) as a parameter that returns a C and takes no parameters.

In other words, it's purely declarative and has no effect on the program.

This is an example of the most vexing parse.

Even if it we fixed that (with C c((C())) or C c{C()}) , pre-C++17 most compilers used permission granted by the language to optimise away that "extra" temporary object (and since C++17 they must do so), so at best you'd probably only see the output from a single default constructor invocation.

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35
Bathsheba
  • 231,907
  • 34
  • 361
  • 483