Search code examples
c++most-vexing-parsetemporary-objects

Miscellaneous temporary object T()


Consider this code :

int main()
{
    int i(6); //this will result in i==6,but consider next initializations

    int j(int()); 

    T * p2 = new T(); 
}

I find that the value of j is 1, but this should be 0 because int() is a temporary with value equal to 0.

Also, the syntax for the new operator is new typename, but here T() will be a temporary object instead of a type name.


Solution

  • int j(int()); 
    

    This doesn't declare an object. Instead it declares a function which takes a function as argument, and returns int. The type of the function which it takes as argument is this :

     typedef int (*funtype)();
    

    That, is, a function which returns int, and takes nothing as argument.

    The parsing of such a declaration is commonly known as:


    And in the new syntax, T() doesn't create a temporary object. That is not how it is to be seen. Instead, you've to look at the entire expression new T() which first allocates memory for an object of type T, and then construct the object in that memory. If T is a user-defined type, then it calls the default constructor to construct the object, after allocating the memory.