Constancy in D constructors

My previous question discussed creating a copy constructor as follows:

struct Foo {
    int i;

    this(int j) { i = j; }

    this(Foo rhs) { this = rhs; }
}

void main()
{
    auto f = Foo(5);
    auto g = new Foo(f);
}

But if I make it iimmutable, the constructor will not compile with

Error: it is not possible to change the structure of this Foo with immutable members

Why is this so? I got the impression that immutable members of a class or structure do not become immutable until the end of the constructor is reached.

+4
source share
2 answers

. , immutable. , , . , , , , , , const immutable . . .

struct Foo
{
    int i;

    this(int j) { i = j; }

    this(Foo rhs) { this = rhs; }
}

void main()
{
    immutable f = Foo(5);
}

. , , - postblit, const immutable (-, , - , - , , , , , ). , postblit, ( , , , ).

, , . , , immutable, immutable ( structs, , , , , ):

class Foo
{
    int i;

    this(int j) { i = j; }
}

void main()
{
    auto f = new immutable Foo(5);
}

:

q.d(10): Error: mutable method q.Foo.this is not callable using a immutable object
q.d(10): Error: no constructor for Foo

. immutable

class Foo
{
    int i;

    this(int j) immutable { i = j; }
}

, , Foo, immutable, , ( ). , . .

class Foo
{
    int i;

    this(int j) { i = j; }

    this(int j) immutable { i = j; }
}

, , . , , pure.

class Foo
{
    int i;

    this(int j) pure { i = j; }
}

, , ( pure , , , ) , Foo , , Foo, , const immutable . , , pure, , , , , .

, , const immutable, . , , const immutable .

+8

structs immutable , , , , .

, :

struct Foo {
    immutable int i;

    this(int j) { i = j; }

    this(in Foo rhs) { this.i = rhs.i; }
}
+2

Source: https://habr.com/ru/post/1544669/


All Articles