What guarantees does D 'const' provide, compared to C++?
Jonathan M Davis
jmdavisProg at gmx.com
Thu Aug 16 19:02:45 PDT 2012
On Friday, August 17, 2012 03:00:34 Chris Cain wrote:
> On Friday, 17 August 2012 at 00:44:20 UTC, Chris Cain wrote:
> > Also, D's const is _not_ a guarantee that there are no mutable
> > references to something. That'd be immutable.
>
> And, by the way, I'd call this a bug (not sure if reported yet):
>
>
>
> int yourGlobalCounter;
>
> struct S
> {
> int*[] items;
>
> this(int i)
> {
> items = new int*[1];
> items[0] = &yourGlobalCounter;
> yourGlobalCounter = i;
> }
>
> ref const(int*[]) getItems() const
> {
> ++yourGlobalCounter;
> return items;
> }
> }
>
> import std.stdio;
>
> void main() {
> immutable(S) s = immutable(S)(0);
> auto it = s.getItems();
> writeln(*it[0]);
> s.getItems();
> writeln(*it[0]);
> }
How is it a bug? The variable that you're altering is not part of the object.
That's part of why having pure with const in so valuable. It prevents stuff
like what you're doing here.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list