On Fri, 20 Jul 2012 14:50:19 +0100, Namespace <rswhi...@googlemail.com> wrote:

New question:

I have this code:
[code]
import std.stdio;

struct Test {
public:
        this(int i = 0) {
                writeln("CTOR");
        }

        this(this) {
                writeln("COPY CTOR");
        }

        ~this() {
                writeln("DTOR");
        }
}

void main() {
        Test[] _arr;

        _arr ~= Test(0);

        writeln("end main");
}
[/code]

And as output i see:

CTOR
COPY CTOR
DTOR
end main

Why on earth....?

I create a struct Test. It's not a local variable, it's directly assigned,
but it is copied and the original is destroyed. Why?

Because that's how assignment works, rhs is evaluated, struct is constructed, then assigned to lhs, lhs copies the variable into the array. Your variable is a struct, so it is copied. Use a pointer instead and the pointer is copied into the array. Use a reference and the reference is copied into the array. The variable, whatever it is, is /always/ copied into the array.

It's a long standing optimisation issue and the reason for the recent distinction between lvalues and rvalues made in C++0x for their new 'move' optimisation where assignments involving rvalues/temporaries can move the rvalue instead of copying - or something like that, I'm a bit vague having watched a vid a few days back and not paying a lot of attention to it, sorry.

Does:

_arr[0] = Test(0);

avoid the copy construction?

R

Reply via email to