2

How can an object replace itself in ASNI C++ ? I want a function like foo->replaceBy(bar) which will cause object foo to delete itself and replace pointer by bar

if (foo->isFoo())
{
    foo->replaceBy(bar);
}

ASSERT(foo->isFoo(), false);
ASSERT(foo->isBar(), true);
tartakynov
  • 2,408
  • 2
  • 24
  • 22

3 Answers3

1

You cannot do this unless you pass a pointer to the pointer or a reference to the pointer (example here):

void replaceBy(Foo*& foo, Foo* bar) {
  delete foo;
  foo = bar;
}

//...

foo->replaceBy(foo, bar);

Which would defeat the purpose of replaceBy being a non-static member function.


There is also the überevil macro way to do this (don't):

#define FOO_REPLACE_BY(foo, bar) do {delete foo; foo = bar;} while(0)

I recommend that you overload operator= and stay away from pointers when possible, or at least use smart pointers (which allow for pointer assignment without memory leaks).

  • Well, foo isn't _necessarily_ a pointer, it could be an object with a -> overload containing a pointer. Exploring that option is still nothing to recommend though, and I'm not sure const-ness even makes it an option if you would :-) – Joachim Isaksson Feb 09 '12 at 16:57
1

A pointer cannot replace itself – the object can of course modify itself but this is const, and since there may be more than one pointer pointing to an object there is logically no way how an object may know which pointer it belongs to (it simply doesn’t belong to a single or even any pointer).

However, maybe the Envelope–Letter pattern is of help for your particular problem.

Konrad Rudolph
  • 482,603
  • 120
  • 884
  • 1,141
0

With the PIMPL idiom it's easy to effectively let objects take each others place: The Pimpl Idiom in practice

Perhaps you also want a swap method to swap the contents of two objects. https://stackoverflow.com/a/843418/1149664

Community
  • 1
  • 1
Johan Lundberg
  • 23,281
  • 9
  • 67
  • 91