Re: Copy constructor not being called on function return

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hi Stuart,

> It looks like it optimises the temporary out.

That is correct, even in non-optimized code, the compiler can (and should)
"optimize the temporary out".

> I would have expected to see a constructor followed by a copy constructor, and
then 2 destructors.

Except for "named return value optimization" (NRVO), which means the
compiler can avoiding doing that in several circumstances.

You should not rely on side-effects in your copy constructor.

> Is there any way to force the copy constructor to be called in the assignment
of myfoo to getFoo()?

Yes, you can make an explicit method which does copy construction, and call
that instead of using the standard copy constructor.

> I have a case where it is vital that the copy constructor is run in this
instance as the the temporary (f) references data which goes out of scope in
getFoo() and so myfoo has references to already released memory - the copy
constructor deals with this elegantly.

In that case, you may want to make sure that you use std::swap semantics to
change ownership, or use an explicit method rather than the copy-constructor
to handle this situation.

I recommend Herb Sutter's books Exceptional C++, More Exceptional C++, C++
Coding Style, and Exceptional C++ Style.  (Hmmm, I guess I'm just a Herb
Sutter fanboy.)

Sincerely,
--Eljay


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux