Copy instead of reference?

Namespace rswhite4 at googlemail.com
Thu May 23 04:34:06 PDT 2013


On Thursday, 23 May 2013 at 11:31:19 UTC, Simen Kjaeraas wrote:
> On Thu, 23 May 2013 13:29:49 +0200, Namespace 
> <rswhite4 at googlemail.com> wrote:
>
>> That was what I also expected. But opAssign is not called.
>
> Because you have a postblit. It's called instead of opAssign.

[code]
import std.stdio;
import std.c.string : memcpy;

struct A {
public:
	int id;

	this(int id) {
		writeln("CTor ", id);

		this.id = id;
	}

	this(this) {
		writeln("Postblit ", this.id);

		this.id *= 2;
	}

	void opAssign(ref const A a) {
		writeln("opAssign L: ", a.id);
		this.id = a.id;
	}

	void opAssign(const A a) {
		writeln("opAssign R ", a.id);
		memcpy(&this, &a, A.sizeof);
	}

	~this() {
		writeln("DTor ", this.id);
	}
}

class B {
private:
	A _a;

public:
	this() {
		this._a = A(42);
	}

	ref A getA() {
		writeln("Return A");
		return this._a;
	}
}

void main() {
	B b = new B();
	A a = b.getA();
}
[/code]

Output:
----
CTor 42
opAssign R 42
DTor 42
Return A
Postblit 42
DTor 84
DTor 42
----

Postblit, no opAssign call.


More information about the Digitalmars-d-learn mailing list