full copies on assignment
John Nixon via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue May 24 07:29:53 PDT 2016
1 import std.stdio;
2
3 struct CS{
4 char[] t;
5 CS opAssign(const CS rhs){
6 writeln("CS.opAssign called");
7 this.t = rhs.t.dup;
8 return this;}
9 };
10 void test_fun(const ref CS rhs){
11 CS cs = rhs;//error cannot implicitly convert expression
(rhs) of type const(CS) to CS
12 CS cs;// these two lines in place of the line above
13 cs = rhs;//now give a program that runs correctly but needs
CS.opAssign
14 writeln("cs = ",cs);}
15
16 void main(){
17 CS rhs;
18 rhs.t="string".dup;
19 test_fun(rhs);
20 return;}
In the above program I noticed the impossibility of compiling a
declaration of a struct and its assignment in the same line (line
11) inside a function which has, as a parameter, a const ref to
the RHS of the assignment. This naively doesn’t seem right
because the RHS of an assignment should not be altered by it. On
investigating further, I could compile the program (with DMD64 D
Compiler v2.071.0) by adding CS.opAssign as indicated and
splitting line 11 into lines 12 and 13 as the comments suggest.
This has do to with D not making a full (deep) copy on assignment
of a CS because it contains a char[], instead giving a pointer to
it that could be used to change it. I think full copies should be
made on assignment regardless of type.
It seems to me that shallow copying of objects is partially in
conflict with the const system, and full copying should be the
default in assignment (perhaps over-ridable by using a keyword eg
alias) which would simplify the const system not giving access to
pointers, and would allow the above program to compile in the way
I first thought of (without CS.opAssign and lines 12 and 13).
I think this is almost the same issue as discussed in “Copying
structs with pointers” on 2011-07-20
More information about the Digitalmars-d-learn
mailing list