What guarantees does D 'const' provide, compared to C++?
Steven Schveighoffer
schveiguy at yahoo.com
Fri Sep 7 06:42:20 PDT 2012
On Thu, 16 Aug 2012 18:14:27 -0400, Mehrdad <wfunction at hotmail.com> wrote:
> Something I'm having trouble undertanding/remembering (sorry, you've
> probaby already explained it a billion times)...
>
> I remember being told many times that D's 'const' provides stronger
> guarantees than C++'s 'const'.
>
> I just wanted to clarify, is that true for 'const' itself, or is that
> referring only to when 'const' is used with other D-specific features
> (immutable, etc.)?
I know this is old, just going through my backlog of unread newsgroup
posts.
someone else correctly pointed out that const guarantees make it a viable
interface for both immutable and mutable data. In other words, it
provides the ability to write a function that accepts both mutable and
immutable data, rather than having to write two such functions that would
be identical.
I look at it like this:
immutable provides guarantees such that statically-checked pure is
possible.
const provides guarantees such that I don't have to repeat myself for
everything!
inout provides similar benefits as const, but allows me to to use chaining
without repeating myself for everything.
>
> If it's the former, is there some example piece of code in each
> language, for comparison, that shows how the compiler can infer more
> from D's const than C++'s?
It's the latter, not the former. The compiler cannot make any assumptions
unless the other guarantees (particularly immutable) are involved.
For example, consider the following function:
int foo(const int *x, int *y)
{
*y += *x;
return *x;
}
If compiled without any context, the compiler *must* re-load *x from
memory, because potentially x == y.
However, if called like this:
int bar(immutable int *x, int *y)
{
return foo(x, y);
}
now, if foo is inlined inside of bar, it *can* make the assumption that x
!= y, and so a reload of *x is not necessary (it must be unchanged).
-Steve
More information about the Digitalmars-d
mailing list