I'm learning about copy-constructors, and I have a test program with two functions: one to take an object of a class by value and show that its copy-constructor is called, and another to show that the copy-constructor is called when returning by value. Here's the code:
The first function uses the copy-constructor as it should, but the second doesn't. The instructions for that function are to create a local object of the class and return it by value; isn't that what I've done?
The returned object doesn't get copied unless it has somewhere to get copied to.
try this:
CopyConst obj( localObj() );
Of course.... the compiler is free to optimize away copies it finds are unnecessary. Both of these functions, for example, could have the copy ctor calls optimized away.
Yeah, I guess that might be what's happening. I tried that and also CopyConst obj = localObj();, but that didn't work either. It's not really important to have this working, and at least I know why it's not.