Q: How can I make a class act like a value type (such as struct)

Myron Alexander someone at somewhere.com
Sun May 27 17:45:42 PDT 2007


Bill Baxter wrote:
> You seem to have solved your problem using structs w/ private, but just 
> FYI you can make classes be allocated on the stack using the 'scope' 
> keyword.
> 
>  void something()
>  {
>     auto foo = new SomeClass(); // foo on the heap
>     scope bar = new SomeClass(); // bar on the stack
>     . . .
> 
>  }
> 
> And I think if you put scope in the class declaration it makes you use 
> 'scope' every time you use the class (? I think...):
> 
> scope class SomeClass()
> {
>    . . .
> }
> 
> I tried that once long ago, but never have been able to think of a case 
> where that would be better than just using a struct.  I guess if you 
> want it to implement an interface...
> 
> --bb

For my library, I use Box to pass values around. My simple test seems to 
show that a scope class can be assigned to a box. The only functionality 
I cannot provide with scope classes is the opCall that I am using.

I whipped up a simple test:

import std.stdio;
import std.boxer;

scope class Xx {
    this (char[] v = "Default") {
       value = v;
    }

    //~ static Xx opCall (char[] v) {
    //~    return new Xx(v);
    //~ }

    private char[] value;

    char[] toString () {
       return value;
    }
}

void dobe (Box b) {
    writefln ("%s", b);
}

void main () {
    scope x = new Xx();

    Box y = box (x);

    dobe (y);
}

If I uncomment the opCall, I get the following compiler error:
scope_box.d(9): Error: functions cannot return auto scope_box.Xx

Luckily, the struct works for my case so I am ok :) I also heard that 
structs are getting constructors which is double bonus.

Regards,

Myron.


More information about the Digitalmars-d-learn mailing list