On Tuesday, 6 March 2018 at 10:49:48 UTC, Dukc wrote:
On Monday, 5 March 2018 at 10:57:35 UTC, Jonathan M Davis wrote (in the article):
The problem is that the entire object must be fully initialized before the body of the postblit constructor is run. That means that any member variables which are const or immutable are stuck at whatever they were in the original object, because it would violate the type system to mutate them. And if an object is const or immutable, then that's all of the members.


I think we have a misunderstanding here. According to that, this would not compile (imports left out):

struct placeAtWorldMap
{   char[] title;
    int[2] coordsMicroDeg;

    this(this)
    {   title = title.dup;
    }
}
void main()
{   char[] title = "London bridge".dup;
    const place = placeAtWorldMap(title, [51_508_038, -87_693]);
    const samePlace = place;
    "falling down ".copy(title);
    place.title.writeln; // falling down
    samePlace.title.writeln; // London bridge
    readln;
}

...but it compiles and correctly runs, and I'm happy about that.

Quote from the article:

. That means that any member
variables which are const or immutable are stuck at whatever they were in the original object, because it would violate the type system to mutate them

Meaning that if you declare your `title` member `const char[] title`, you can't change it in the postblit, but you could set it in the constructor.

```
import std.array;
import std.stdio;
import std.algorithm;

struct placeAtWorldMap
{   const char[] title;
    int[2] coordsMicroDeg;

    this(char[] name)
    {
this.title = name.idup; // you can assign const members here
    }

    this(char[] name, int[2] coords)
    {
        this.title = name;
        this.coordsMicroDeg = coords;
    }

    this(this)
    {//   title = title.dup;    // doesn't work anymore
    }
}

void main()
{   char[] title = "London bridge".dup;
    const place = placeAtWorldMap(title, [51_508_038, -87_693]);
    const newPlace = placeAtWorldMap("Big Ben".dup);
    const samePlace = place;
    "falling down ".copy(title);
    place.title.writeln; // falling down
    samePlace.title.writeln; // London bridge
    newPlace.title.writeln;      // Big Ben
}
```

Reply via email to