const and immutable members
Jonathan M Davis
jmdavisProg at gmx.com
Mon Sep 23 15:08:29 PDT 2013
On Monday, September 23, 2013 13:49:59 Daniel Davidson wrote:
> > But if your concern is client code messing with your member
> > variable, then
> > don't give them access to it in the first place.
>
> Not quite as much messing with the member as messing with what it
> points to. In the setup - rich data, read from the wire or disk,
> lots of nesting of lists, associative arrays, json like data,
> etc, the POD data is being read and stored into nested structs
> all prior to coming to my class. I want to ensure that the memory
> that I know both of us (S and the client code who built data to
> pass to S and other users) is not being modified.
Then your member variable is going to be a reference type, and you can make it
tail-const - except in the case of AAs, but if you simply return a const AA
from a getter, then client code can't change it. In order to actually have
tail-const AAs, we'd need something like Rebindable but for AAs (or maybe
Rebindable could be made to work with AAs). But in general, if you want to
share data and want to avoid copying, making the data is a good move, but you
do it by making the data immutable and not what refers to it (i.e. tail-
immutable). Then the data itself can be safely shared, but you don't run into
all of the problems that come when you make a member variable in a struct
fully const or immutable.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list