constructor invocation mechanism

 ̄綄美尐妖づ 提交于 2019-11-26 09:52:43

问题


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.


回答1:


Case 1)

m is interpreted as a function return my and taking no arguments. To see the expected output remove () i.e use my m;

Case 2)

This is something better known as the "Most vexing parse".

n is interpreted as a function returning my that takes an argument of type pointer to function returning my taking 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 to my n = my(). Now the rvalue expression my() creates a temporary[i.e a call to the default constructor] and n is 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.




回答2:


Like Prasoon, I suspect the C++ compiler is parsing your code in a way you don't expect. For example, I think it is parsing the line

my m();

as a function prototype declaration, not as a variable declaration and call to the constructor - hence why you see no output.



来源:https://stackoverflow.com/questions/4283576/constructor-invocation-mechanism

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!