~= call copy ctor?
Matthias Walter
xammy at xammy.info
Thu Jul 19 05:56:55 PDT 2012
On 07/19/2012 02:27 PM, Namespace wrote:
> I have a 2 questions.
>
> I have this code:
>
> [code]
> import std.stdio;
>
> struct Test {
> public:
> this(int i = 0) {
> writeln("Test CTor.");
> }
>
> this(this) {
> writeln("Test Copy CTor");
> }
>
> ~this() {
> writeln("Test DTor");
> }
> }
>
> Test[] _arr;
>
> void copy_save(Test t) {
> _arr ~= t;
> }
>
> void by_ref_save(ref Test t) {
> _arr ~= t;
> }
>
> [/code]
>
> Why get i with
>
> [code]
> void main() {
> Test t = 42;
>
> by_ref_save(t);
> }
> [/code]
>
> this output:
>
> Test CTor.
> Test Copy CTor
> Test DTor
As you mentioned in the subject the copy constructor is not called while
the struct is passed by reference but on array concatenation.
But this must occur since the array has its memory region and the
original variable t in main() also has. Since they are different, at
some point the struct must be copied from t in main() into the array.
The "ref" only ensures that it is passed via reference (a pointer to the
memory of t in main()) to the function by_ref_save().
> And the same if i have this:
>
> [code]
> void main() {
> Test t = 42;
>
> copy_save(t);
> }
> [/code]
>
> t is already a clone. Why it is copied again?
Here it is once copied from t in main() into the local variable t in
copy_save() and then copied (as in your 1st example) into the array.
Imagine the copy_save routine is in a different module and only its
signature is exposed to main. When calling the function, the compiler
does not know what happens inside copy_save but it must put the variable
onto the stack at the position of the first parameter (well, in this
case it is probably put into a CPU register, but that doesn't matter here).
Then, when copy_save is invoked it only knows the local variable which
it then copies into the array memory (after enlarging the array).
It *may* be the when you enable compiler optimizations (-O -inline) that
copy_save gets inlined and hence the compiler can optimize one of the
copy calls away. But that I don't know for sure.
Best regards,
Matthias
More information about the Digitalmars-d-learn
mailing list