Topic: Q: returning object from function
Author: clamage@Eng.Sun.COM (Steve Clamage)
Date: 1996/01/10 Raw View
In article 5ig@dub-news-svc-4.compuserve.com,
100754.2730@compuserve.com (Martin Aupperle) writes:
>I have
> X x = f();
>with some non-trivial class X. If I understand the DWP (12.2:
>temporary objects) right, it is implementation dependent whether
>- a temporary is constructed (on the stack) that is used to initialize
>x
>- the result is constructed in x's memory directly.
>The difference is the construction of the temporary. If my observation
>is true, there a strong requirement concerning the behaviour of the
>copy constructor, if one wants to write portable software.
>Is that true?
In many kinds of expressions, the compiler is allowed to introduce or
to optimize away the creation and deletion of a temporary variable.
Your example is one of those cases. Another is
X x = y;
which literally means
X x(X(y));
but which may be interpreted as
X x(y);
In such cases, the rules of C++ say in effect that the semantics of the
program are the same whether the temporary is created or not. Thus, you
have to design your classes so that program correctness does not depend
on whether extra temporaries are created.
Usually that means that constructors and destructors should have
complementary side effects, and you have to be careful about acquiring
locks or other scarce resources in a copy constructor.
---
Steve Clamage, stephen.clamage@eng.sun.com
---
[ comp.std.c++ is moderated. Submission address: std-c++@ncar.ucar.edu.
Contact address: std-c++-request@ncar.ucar.edu. The moderation policy
is summarized in http://dogbert.lbl.gov/~matt/std-c++/policy.html. ]