Const ref and rvalues again...
martin
kinke at libero.it
Wed Nov 7 17:45:11 PST 2012
On Wednesday, 7 November 2012 at 21:39:52 UTC, Timon Gehr wrote:
> You can pass him an object that does not support operations you
> want to preclude. He does not have to _know_, that your book is
> not changed when he reads it. This is an implementation detail.
> In fact, you could make the book save away his reading schedule
> without him noticing.
I don't see where you want to go with this. Do you suggest
creating tailored objects (book variants) for each function
you're gonna pass it to just to satisfy perfect theoretical
encapsulation? So foo() shouldn't be able to change the author =>
change from inout author reference to const reference? bar()
should only be allowed to read the book title, not the actual
book contents => hide that string? ;) For the sake of simplicity,
by using const we have the ability to at least control if the
object can be modified or not. So although my colleague doesn't
have to _know_ that he can't modify my book in any way (or know
that the book is modifiable in the first place), using const is a
primitive but practical way for me to prevent him from doing so.
In the context of this rvalue => (const) ref discussion, const is
useful due to a number of reasons.
1) All possible side effects of the function invokation are
required to be directly visible by the caller. Some people may
find that annoying, but I find it useful, and there's a
single-line workaround (lvalue declaration) for the (in my
opinion very rare) cases where a potential side-effect is either
known not to occur or simply uninteresting (requiring exact
knowledge about the function implementation, always, i.e., during
the whole life-time of that code!).
2) Say we pass a literal string (rvalue) to a const ref
parameter. The location of the string in memory can then be
freely chosen by the compiler, possibly in a static data segment
of the binary (literal optimization - only one location for
multiple occurrences). If the parameter was a mutable ref, the
compiler should probably allocate a copy on the stack before
calling the function, otherwise the literal may not be the same
when accessed later on, potentially causing funny bugs.
3) Implicit type conversion isn't a problem. Say we pass an int
rvalue to a mutable double ref parameter. The parameter will then
be a reference to another rvalue (the int cast to a double) and
altering it (the hidden double rvalue) may not really be what the
coder intended. Afaik D doesn't support implicit casting for
user-defined types, so that may not be a problem (for now at
least).
More information about the Digitalmars-d
mailing list