is my code to get CTFE instantiated object valid D ?
Steven Schveighoffer via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Fri May 27 13:56:06 PDT 2016
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
More information about the Digitalmars-d-learn
mailing list