Topic: Q: f( const T )


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:
>If I have a function declared as
>
>  f( const T );
>
>will a local T be created and initialized with the copy constructor?
>I hope so, but people pointed out to me that f cannot change anything
>in the object and therefore can work on the caller's object too, and
>therefore a compiler may optimize away the local object.
>What about mutable members? Since we now can have these, it makes a
>difference. Who is right?

The semantics implemented by the compiler must be those of pass by value,
whatever mechanism is actually used. In particular, if the program
contains only code with defined behavior, the actual argument must
not be changed by the call to f() -- whether the formal argument is
declared const or not.

In particular, if type T has a mutable member, the compiler cannot pass
the actual argument by reference unless it can prove that the argument
is in fact never altered.

If the formal argument is declared const and has no mutable members,
casting away const and attempting to modify the parameter has undefined
results.

The fundamental rule is the "as-if" rule. The language definition
describes the effects of various constructs. The standard describes an
abstract machine for purposes of explanation of the required effects.
An implementation that behaves (so far as a valid program can detect)
as if it were the abstract machine is a valid implementation.
---
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. ]