digitalmars.D.learn - Initialization of mutable struct by immutable struct
It's may be conceptual question. For example I want to create immutable struct instance in module scope like a global default value. But then I need to make mutable copy of this global struct variable in order to init some class instance with it (for example). Main requirement is to do this with fewer coding. But maybe there is some usual way for implementing such functionality. Ideas calling to mind are: 1) Append dup() property to struct (like it is in arrays) 2) Create some specific constructor for example struct A { this(string some) immutable { _some = some; } this(immutable(A) a) { _some = a._some; } private string _some; } class B { this(A a) { _a = a; } private A _a; } immutable(A) globalA = A("Global"); void main() { B b = new B( A(globalA) ); } 3) Using postblit copy constructor. But I don't know if it is possible to write like this: struct A { this(string some) immutable { _some = some; } this(immutable(this)) { _some = _some; } private string _some; } Because I have not used it. And documentation for it is short. 4) Using opAssign. But this is not initialization but assigment. I have not dealed a lot with all of these const, shared, immutable in D a lot. So I wrote my programmes (in most cases) like they are not exist. Now I want to try write correctly.
Nov 27 2013
In addition to my letter I wrote some test code following the message. I found out that I can use copy constructor signature: this(immutable(this)), to get a mutable copy of immutable struct. But this is not working with this(const(this)). My thoughts were that if I would define some method parameter as const so it will accept both mutable and immutable arguments. Is there some exceptional situation that it's not true for copy constructors or is it a bug or is it my misunderstanding of this question? //------------------- import std.stdio; struct A { this(string some) immutable { _some = some; } //this(immutable(A) a) //{ _some = a._some; } this(immutable(this)) {} //This is working with immutable //this(const(this)) {} //But this is not working with immutable void printSome() { writeln(_some); } private string _some; } class B { this(A a) { _a = a; } private A _a; void printA() { _a.printSome(); } } immutable(A) globalA = immutable(A)("Global"); void main() { //B b = new B( A(globalA) ); B b = new B( globalA ); //immutable globalA copying into mutable b.printA(); } //-------------- Also available at: http://dpaste.dzfl.pl/3c89185e
Nov 27 2013