Struct copy and destruction

spir denis.spir at gmail.com
Sat Apr 9 02:47:11 PDT 2011


On 04/09/2011 10:00 AM, Morlan wrote:
> The following code:
>
> //***************************************************
> import std.conv, std.stdio;
>
> struct Slice {
> 	int[] buff;
> 	this(size_t len) {
> 		buff = new int[len];
> 	}
> 	this(this) {
> 		buff = buff.dup;
> 		writeln("postblit");
> 	}
> }
>
> struct S {
> 	string name;
> 	Slice slc;
> 	this(string name) {
> 		writeln(name, " constructor");
> 		this.name = name;
> 	}
> 	~this() {
> 		writeln(name, " destructor");
> 	}
> }
>
> void main() {
> 	auto s1 = S("s1");
> 	auto s2 = S("s2");
> 	s1 = s2;
> 	writeln("after assignment");
> }
> //***********************************************
>
> produces the following output:
>
> s1 constructor
> s2 constructor
> postblit
> s1 destructor
> after assignment
> s2 destructor
> s2 destructor
>
> Note the "s1 destructor" line after "postblit". I cannot find any justification for the destructor
> call in this place either in the TDPL book or in the Language Reference. Is this behaviour to be
> expected? If so I would be grateful for the proper reference. Otherwise is it a bug?

This may not reflect actual processing sequence; instead be caused by output, 
precisely the order in which strings are written on the terminal, due to 
queuing. I often have such messy outputs for compile / build error logging, for 
instance, like:
    error 1
    error 2
    compilation failed	// should be last
    error 3
There is certainly a way to flush output streams (stdout) in D (someone 
knows?). Then, you can actually check.

Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d mailing list