Okay, so what is the expected and actual output?
Printable View
Okay, so what is the expected and actual output?
I expect the copy constructor to be called three times, but its called 2 times. Why?
Because one of those copy constructor invocations that you expected was elided by the compiler. (In particular, there is no need to create a temporary to be copied to the object to be initialised since the object to be initialised can be initialised as a copy of the local variable.)Quote:
Originally Posted by StGuru
Go back to my post #21:
In other words, you can't predict how many times a copy constructor or assignment operator is called when given code that can generate multiple calls to these functions.Quote:
Also note that copy construction can be removed by the compiler if it is detected that the copy is superfluous
That's why when you write a user-defined assignment operator or copy constructor, you can't write it with the expectation it will be called a certain number of times. These operations could be called once, twice, three times, ten times, or no times, given the same piece of code and compiled using different compilers and/or compiler options.
Regards,
Paul McKenzie
Does it mean that the compiler does not create copy for the returning object since it already been copied (before passed by value as a parameter to a function and copy constructor called)?
Quote:
Does it mean that the compiler does not create copy....
You've got the general idea. As a theme you can expect that modern compiler optimizations take every effort to fashion results which "mean" exactly the same thing as what you've written, but with as few steps as possible, given the level of research. Compilers have improved dramatically over the years.
Even when optimizations are turned off, some of the very obvious ones are still used, like genuinely superfluous copies.