Abstract type
Abstract type

Reputation: 1921

How to set an immutable member after struct default construction?

I have a struct whose one of the member is immutable so it can only be initialized in a constructor. However since it's a struct, an instance can be declared without calling a constructor and then initialized later using a copy constructor (or any other function).

Problem: the call is forbidden by the compiler since the immutable member is supposed to be already set.

Demonstration of the problem:

struct Member
{
    immutable int value;
}

struct Foo
{
    Member memb;
    this(string param)
    {
        memb = Member(1);
    }
    void reset(string name){}
}

void main(string[] args)
{
    // here error
    Foo foo;
    foo = Foo("test");

    // here memb is never set
    Foo bar; 
    bar.reset("test");
}

In the real life application, what happens is the second case. No error is generated but the program doesn't work well because the immutable member has not been set properly.

I could use a class (because in classes the default constructor can be rewritten) but I don't want to because the struct is more a less POD.

edit

Important detail:The parameter to call the struct constructor directly are not all directly available. This is not well represented in the demo.

Upvotes: 0

Views: 62

Answers (1)

Adam D. Ruppe
Adam D. Ruppe

Reputation: 25605

This is what @disable this(); is for - disabling the default constructor, forcing it to be constructed explicitly at the declaration site (or, in the constructor of a containing aggregate; e.g. the constructor of a class if your struct is a member).

While you cannot define a default constructor, you can disable it and force the user to use one of your other constructors or static factory methods. Do that and make them set the immutable member.

Upvotes: 1

Related Questions