*
ja****@gmail.com:
Consider the code below. The output is the following two lines:
0xbfc78090
0xbfc780a0
This proves that the variable m in main() is not the very same instance
of MyClass as temp_m in hello(). Hence (?) m is created as copy of
temp_m. But the copy constructor is not called. Contradiction. Where am
I thinking incorrectly?
#include <iostream>
using namespace std;
class MyClass
{
public:
MyClass () {}
MyClass (const MyClass& m)
{
cout << "Copy constructor called!" << endl;
}
};
MyClass hello()
{
MyClass temp_m;
cout << &temp_m << endl;
return temp_m;
}
int main()
{
MyClass m;
m=hello();
cout << &m <<endl;
}
Well, there are two possible misconceptions involved.
First, the '=' in the statement 'm=hello();' is an /assignment/,
invoking the assignment operator, not the copy constructor. The
difference between assignment and copy construction is that assignment
changes the member values of some existing object (perhaps deallocating
already allocated memory), whereas copy construction turns a chunk of
raw, uninitialized memory into an object, a copy. Perhaps you knew
that, but the formulation "creates as a copy of" seems to indicate that
this is indeed the basic misconception; if you'd written 'MyClass m =
hello();' then the "=" would instead denote copy construction.
Second, the compiler is allowed to optimize away copy construction in
certain situations, /regardless of whether the copy constructor has side
effects or not/. The copy constructor is very very special, in that the
compiler, in these relevant situations, is allowed to assume that what
the copy constructor does is to actually construct a perfect copy, and
nothing else whatsoever. These situations include the 'MyClass m =
hello();' initialization, as well as the call to 'hello()' itself (where
this optimization is known as RVO, Return Value Optimization).
This also means that C++ tests that ask you to count the number of copy
constructor calls in a piece of code, ending up with some exact number,
are generally tests made by incompetents (although in some pieces of
code you can be sure of the number of calls).
And unfortunately that includes most C++ tests, even some that cost $$$.
Hth.,
- Alf
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?