mercredi 15 avril 2020

Optional pointer ownership

Let's consider this class, which owns or views a pointer depending on how it is constructed.

template<class T>
class OptionalUniquePtr
{
  public:

    OptionalUniquePtr(p*)
    : m_p(p)
    {}

    OptionalUniquePtr(std::unique_ptr<T>&& p)
    : m_owned_p(std::move(p))
    , m_p(p)
    {}

    T* get()
    {
      return m_p;
    }

 private:

   std::unique_ptr<T> m_owned_p;
   T *m_p;
};

Apart from tweaks or optimisations, my question is: is this a bad idea? I'm working on some code that could optionally own or view some pointers:

std::unique_ptr<Bar> b1 = ...;
Bar *b2 = ...;
// one million lines later
Foo f1(std::move(b1)); // ownership transfered to f1
Foo f2(b2); // just viewing b2, caller manages lifetime. Risky, but usually owners have long lifetime

I want Foo to be flexible to accept both, so it could have an OptionalUniquePtr inside. An alternative is templatise Foo like this

Foo<std::unique_ptr<Bar>> f1(std::move(b1));
Foo<Bar*> f1(b2);

The advantage of this second approach is to be more explicit about memory ownership.

Another alternative is to use std::shared_ptr to start with, but in huge codebases this is not feasible.

What is the community opinion on OptionalUniquePtr?

Thanks

Simone

Aucun commentaire:

Enregistrer un commentaire