mardi 23 mai 2017

Writing a wrapper class without copying or dereferencing

Suppose I want to create a wrapper around another class instance, but I don't want to move or copy that original class instance. Maybe the instance I want to wrap is declared on the heap and lots of other stuff points to it.

I could do something like this:

class SomeClass {
 public:
  void Bar(int);
};

class Wrapper {
 public:
  Wrapper(SomeClass *some_class) {
    data = some_class;
  }

  void Foo() {
    data->Bar(42);
  }

 private:
  SomeClass *data;
};

However this adds a level of indirection, because the data pointer has to be dereferenced. Compare to this implementation which would make a copy of SomeClass:

class Wrapper {
 public:
  Wrapper(SomeClass some_class) : data(some_class) {}

  void Foo() {
    data.Bar(42);
  }

 private:
  SomeClass data;
};

That avoids the dereference but now it's not a wrapper (plus the overhead of the copy).

Is there a way to write the wrapper in a way that avoids the dereference without copying or moving the wrapped object?

I was thinking you could do something like static casting a SomeClass instance to a Wrapper instance since the data layout of the two classes should be the same (since there's no vtable or extra data in the Wrapper class), but that would never get past a code review.

Aucun commentaire:

Enregistrer un commentaire