2

This is a very basic question about C++. Why isn't a constructor invoked for the statement "A x(A())"?

In the code that follows - which I have run with g++ 4.8.2 - the constructor (as well as the destructor) is called only once. This may be due to optimization but I am curious about the type of x - reported by typeid - which is "A(A (*)())".

#include <iostream>
#include <typeinfo>
#include <cxxabi.h>
using namespace std;

class A{
 public:
 ~A() { cout << "Destructed" << endl; }  
};

int main() {
   int status;

   A x(A());
   cout << abi::__cxa_demangle(typeid(x).name(),0,0,&status) << endl;

   A a ;
   cout << abi::__cxa_demangle(typeid(a).name(),0,0,&status) << endl;

   return 0;
}
argmin
  • 77
  • 4

1 Answers1

3

It's commonly known as c++ vexing parse, which means that pretty much anything that can be parsed as a function declaration will be.

So, A x(A()); is a function declaration indeed, which take a function pointer of type A() as its parameter, and return type is A.

You can add a pair of parentheses to force the compiler to process it as a variable initialization:

A x((A()));

Because it's not legal to surround a formal parameter declaration with parentheses, but it is legal to surround an argument to a function call with parentheses, so by adding a pair of parentheses, we force compilers to see things our way.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405