On 5/27/16 4:20 PM, chmike wrote:
I need to create an app wide singleton instance for my class.
The singleton is immutable, but I want to allow mutable references to
that singleton object so that I can do fast 'is' tests.

I declared this

class Category
{
      protected static immutable Category instance_ = new Category;
      Category instance() { return cast(Category)instance_; }
      ...
}

It compiles and the instance should be instantiated at compile time. I
couldn't check yet.

The public interface of Category is designed so that the object's state
can't be modified and thus remains immutable.

Is this code valid D or is the behavior undefined due to the cast ?

You can cast away immutable. You just can't mutate. Hard to say without seeing what the ... is.

A variant implementation would have a method that modifies the object
but only internally and in a very controlled way to store strings in a
cache for faster access. Would it still be valid D code ?

No. Undefined behavior if you modify immutable data.

-Steve

Reply via email to