3 Answers
3

This is called as copy elision.
The compilers are allowed to do this optimization. Though it is not guaranteed by the standard any commercial compiler will perform this optimization whenever it can.

Standard Reference:

C++03 12.8.15:

[...] This elision of copy operations is
permitted in the following
circumstances (which may be combined
to eliminate multiple copies):

[...]

when a temporary class object that has
not been bound to a reference (12.2)
would be copied to a class object with
the same cv-unqualified type, the copy
operation can be omitted by
constructing the temporary object
directly into the target of the
omitted copy

You might use some compiler settings to disable this optimization, like in case of gcc, from the man page:

-fno-elide-constructor

The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. Specifying this option disables that optimization, and
forces G++ to call the copy constructor in all cases.

However, using this makes your code non portable across different compilers.

It is because of the optimization performed by your compiler. Compilers are permitted to perform such optimizations, though it is not a requirement, thus not guaranteed.

Note an important point that even though the copy-constructor is not invoked eventually, it is semantically required to be accessible. That is, if you make the copy-constructor private, your code will not compile!! It is because the semantic-check is done much before the optimization phase, means the compiler first checks that the copy-constructor is accessible or not; if it is accessible, then only comes the optimization phase where the copy-construction is elided.

Another way of reasoning for the copy constructor to be accessible is that copy elision is not guaranteed. A compiler may or may not perform this optimization since standard does not mandate it. So if there exists a compiler which cannot perform this optimization then it needs the copy constructor to be accessible. So since standard does not enforce the optimization it cannot enforce the optimization to work without the copy constructor.
–
Alok SaveJan 4 '13 at 9:35