Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Moving objects in C++

Name: Cudder !MhMRSATORI 2015-02-03 11:43

C++ has new (constructor), delete (destructor), but what happened to reallocating and moving, something that is so easily done in C?

What gets in the way is that there may be pointers to the moved object, and this is the most common argument against it. In C++11 "move semantics" were introduced which is far more complex and convoluted than the bleedingly obvious solution of... update the pointers to the moved object!

In other words, they could just add a special member function that is called when an object is moved, with one parameter - its new address.

class Bar;
class Foo {
Bar *b;
Foo() { b = 0; }
Foo(Bar *b) {
this->b = b;
}
void move(void *x) {
b->f = x;
}
};

class Bar {
Foo *f;
Bar() { f = 0; }
Bar(Foo *f) {
this->f = f;
}
void move(void *x) {
f->b = x;
}
};


If a Foo is moved, then its Bar needs to be updated, and vice-versa. Of course this doesn't work in all cases because not all objects can know what points to them, but for those that do, the solution is trivial and it makes realloc work. To not provide a language feature for moving any object, just because some of them can't be moved, is absurd.

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List