D1 and read-only views?

Jarrett Billingsley jarrett.billingsley at gmail.com
Fri Apr 10 10:37:47 PDT 2009


On Fri, Apr 10, 2009 at 1:21 PM, Nick Sabalausky <a at a.a> wrote:
> Am I correct in my understanding of the following regarding D1?:
>
> Suppose there's a D1 class like this:
>
> class Foo
> {
>  // Johnny Coder wants the string to be readable from
>  // outside Foo, but not changable from outside Foo.
>  // He handles it as he would an int:
>
>  private char[] _myStr;
>  public char[] myStr()
>  {
>    return _myStr;
>  }
>
>  this()
>  {
>    // Have to awkwardly .dup this in case Foo
>    // itself wants to modify _myStr in-place.
>    _myStr = "bar".dup;
>  }
> }
>
> That contains a bug (in "myStr()") because myStr() simply returns a pointer
> (and length, of course) to the actual data, and the caller could use that to
> change the data:
>
> auto f = new Foo();
> auto str = f.myStr();
> assert(f.myStr() == "bar"); // Ok
> str[0] = 'c';
> assert(f.myStr() == "bar"); // FAIL!
>
> Unlike C and D2, D1's const doesn't create a read-only view, but simply
> means the value is set at compile-time. D1 doesn't have anything else
> comparable to the C or D2 const so if Johnny Coder wants to make his
> interface to Foo safe, his only choice is to make myStr() duplicate the
> string:
>
>  public char[] myStr()
>  {
>    return _myStr.dup;
>  }
>
> Is this all correct?

Yes.


More information about the Digitalmars-d-learn mailing list