Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

c++ - constructor invocation mechanism

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...