This is the mail archive of the
gcc-help@gcc.gnu.org
mailing list for the GCC project.
Re: Copy constructor not being called on function return
- From: John Love-Jensen <eljay at adobe dot com>
- To: Stuart Brooks <stuartb at cat dot co dot za>, GCC-help <gcc-help at gcc dot gnu dot org>
- Date: Mon, 03 Nov 2008 11:42:36 -0600
- Subject: Re: Copy constructor not being called on function return
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