mardi 27 octobre 2015

design headache with unique_ptr

Say we have class Foo:

class Foo {
public:
  ...
};

Foo has an instance method which either transforms the Foo instance into another Foo instance, or returns the same Foo instance:

<some appropriate pointer type to Foo> Foo::tryToTransform() {
  if (canBeTransformed()) {
    <delete this Foo instance>;
    return <new instance of Foo>;
  }
  else {
    return <this instance of Foo>;
  }
}

Client code:

<some appropriate pointer type to Foo> foo = ...;
...
foo = foo->tryToTransform();

This is easy to do with naked pointers:

Foo* Foo::tryToTransform() {
  if (canBeTransformed()) {
    delete this;
    return new Foo(...);
  }
  else {
    return this;
  }
}

Foo* foo = ...;
...
foo = foo->tryToTransform();

But what if the client code uses a unique_ptr instead of a naked pointer? That is, ideally I would like the client code to look like this:

unique_ptr<Foo> foo = ...;
...
foo = foo->tryToTransform();

How should Foo::tryToTransform() be defined in order to enable such (or similar) client code?

Aucun commentaire:

Enregistrer un commentaire