vendredi 27 janvier 2017

enforcing a class to be used only as a shared pointer

In order to prevent bad usage of a class T and shared_ptr (typically, constructing multiple shared_ptrs from the same T*, resulting in double free) I thought to force shared pointers to be used, by making the class constructor private, and adding a factory method to create a shared_ptr.

Question 1: is this a bad approach and why?

I abstracted all the above functionality into this base class template:

#include <memory>

template<typename T>
class add_make_shared : public std::enable_shared_from_this<T>
{
public:
    typedef std::shared_ptr<T> Ptr;

    template<typename... Args>
    static Ptr make_shared(Args&&... args)
    {
        return Ptr(new T(std::forward<Args>(args)...));
    }
};

I also inherit from enable_shared_from_this because it is useful in this scenario.

Then, one is required to do, for every class A:

class A : public add_make_shared<A>
{
private:
    friend class add_make_shared<A>;

    A(...) { ... }

public:
    ...
};

basically:

  • declare add_make_shared as friend, because it needs to construct A
  • declare A's constructor private

(Provided that you answered no to Question 1) Question 2: is this implementation optimal or how can be improved?

For my taste is still a bit verbose, due to the two above points.

Aucun commentaire:

Enregistrer un commentaire