Re: Does binding to const-reference outperform copy-initialization from returned value?
"Niels Dekker - no return address" <invalid@this.is.invalid> wrote in
message news:%236ujDZw2JHA.5244@TK2MSFTNGP04.phx.gbl
Igor Tandetnik wrote:
const Foo& constReference = GetFoo();
const Foo constValue = GetFoo();
In principle, the compiler is allowed to call Foo's copy-constructor
one more time in the second case, compared to the first. However, it
is highly likely the compiler would optimize this extra call away in
a release build. I can't think of any situation where it would be
unable to, off the top of my head.
Thanks, Igor. So "in principle", it would be preferable to bind the
returned value to a const-reference, but in practice (at least for
VC++), copy-initialization performs equally well, right?
Yes - for VC++ and, I expect, any modern compiler. E.g. GCC has a very
sophisticated optimizer, in my experience.
I did some tests, but I couldn't find any difference in behavior,
between the two ways to retrieve the return value.
This seems to prove the point rather nicely, doesn't it?
BTW, I still
wonder if it wouldn't be preferable to skip the copying in Debug mode
as well. I do appreciate being able to step into every line of source
code, while debugging. But it doesn't seem very useful to me to step
into a copy-constructor, if that function is being skipped when the
application is released. What do you think?
I don't have any particular opinion on this issue.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925