struct my
{
my(){ std::cout<<"Default";}
my(const my& m){ std::cout<<"Copy";}
~my(){ std::cout<<"Destructor";}
};
int main()
{
my m(); //1
my n(my()); //2
}
Expected output :
1 ) Default
2 ) Copy
Actual output :
What’s wrong with my understanding of the constructor invoking mechanism?
Note I have omitted header files for brevity.
Case 1)
mis interpreted as a function returnmyand taking no arguments.To see the expected output remove
()i.e usemy m;Case 2)
This is something better known as the “Most vexing parse”.
nis interpreted as a function returningmythat takes an argument of type pointer to function returningmytaking no arguments.To see the expected output in this case try
my n((my()));[Instead of treating as an argument specification as in the former case the compiler would now interpret it as an expression because of the extra()]My interpretation:
my n((my()))is equivalent tomy n = my(). Now the rvalue expressionmy()creates a temporary[i.e a call to the default constructor] andnis copy initialized to that temporary object[no call to the copy-ctor because of some compiler optimization]P.S: I am not 100% sure about the last part of my answer. Correct me if I am wrong.