Move Semantics
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Sep 29 11:23:58 PDT 2015
On 09/29/2015 07:38 AM, Alex wrote:
> See my code here: http://dpaste.dzfl.pl/995c5af59dd6
> Following my code, the inner object I moved does not disappear from the
> array in the source outer object. Why?
> After I moved the inner object to the new outer object, the pointer to
> the outer object remains in the old state, to the source outer object.
The output of the program is too complicated for me to understand what
the expected behavior should be. Going with the text... :)
Some notes:
- Unlike C++, as classes have reference semantics, normally there should
be no need to move class objects around.
* Even so, your expectation of the 'outer' pointer being updated is not
something move() can decide on its own. Moving an object's parts
elsewhere not necessarily require changing the context it operates in.
move() cannot know that being a part of a member associative array (AA)
constitues changing the 'outer' pointer. move() doesn't even know that
the destination location is a part of a memory that is being used by an AA.
- When it is needed to transfer an object from one Outer object to
another, setting the .outer property seems to work:
import std.stdio;
class Outer {
int i;
this (int i) {
writefln("Constructing an Outer at %s.", cast(void*)this);
this.i = i;
}
class Inner {
void workWith(Outer newOuter) {
this.outer = newOuter;
}
void report() {
writefln("I am working with %s. Its i is %s.",
cast(void*)this.outer, this.outer.i);
}
}
}
void main() {
auto o1 = new Outer(1);
auto o2 = new Outer(2);
auto inner = o1.new Outer.Inner();
inner.report();
inner.workWith(o2);
inner.report();
}
(Casting a class variable to void* provides the location of the class
object.)
Prints:
Constructing an Outer at 7F136FB81060.
Constructing an Outer at 7F136FB81080.
I am working with 7F136FB81060. Its i is 1.
I am working with 7F136FB81080. Its i is 2.
- Unrelated note: Unless there is a convincing reason, I recommend that
constructors simply construct objects. Side-effects like objects'
registering themselves should not take place in a constructor. I have
been bitten by that myself and I have heard the same suggestion from
others several times before.
Ali
More information about the Digitalmars-d-learn
mailing list