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

Bill Baxter dnewsgroup at billbaxter.com
Sun May 27 17:18:55 PDT 2007


Myron Alexander wrote:
> Regan Heath wrote:

> The above is one aspect of what I meant as a value object but my manner 
> of use does not need it. I am more concerned with storage and I want my 
> class to be allocated on the stack rather than on the heap so that the 
> GC does not have to bother with it.

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


More information about the Digitalmars-d-learn mailing list