readonly?

Artur Skawina art.08.09 at gmail.com
Wed Jul 11 01:56:23 PDT 2012


On 07/11/12 09:00, Tobias Pankrath wrote:
> On Wednesday, 11 July 2012 at 06:48:59 UTC, David Nadlinger wrote:
>> On Wednesday, 11 July 2012 at 06:34:29 UTC, Tobias Pankrath wrote:
>>>> This escapes a stack reference.
>>>
>>> Ins't b supposed to be allocated on the heap?
>>
>> The Bar instance is, but the pointer to it is not. Making _b a Rebindable instead of using a pointer (to what effectively is a pointer to the real object) should help.
>>
>> David
> 
> Bar b = new Bar;
> auto b2 = &b; // type of b2 is Bar*
> 
> So does it meen, that a pointer of type Bar* does not point to the real object?

Yeah, unfortunately.
Can anybody think of a reason to keep the current (broken) behavior?

> How do I get such a pointer then and which type does it have?

You can use something like this:

   static struct ClassPtr(C) if (is(C==class)) {
      // '__cp' is not the same as what the compiler currently considers a class
      // pointer; it is used here as a container for the reference. This adds the
      // missing level of indirection, which allows for the necessary different
      // (but still compatible) types.
      private C* __cp;

      pure: @safe: nothrow:
      @trusted this(C o) { __cp = cast(C*)o; }
      @trusted C opAssign(C o) { __cp = cast(C*)o; return o; }

      @trusted @property C get() { return cast(C)__cp; }
      @trusted @property const(C) get() const { return cast(C)__cp; }
      alias get this;
   }
   
   // Eg:
   class Bar {}
   class Foo { ClassPtr!(const Bar) _b; void SetBar(const Bar b) { _b = b; } }


And - no - this shouldn't be necessary.

artur


More information about the Digitalmars-d-learn mailing list