I\'ve been working on a way to prevent user of using a class without smart pointers. Thus, forcing them to have the object being heap allocated and managed by smart pointers. In
Create a friend'd factory function that returns a std::unique_ptr
, and make your class have no accessible constructors. But make the destructor available:
#include
class A;
template
std::unique_ptr make_A(Args&& ...args);
class A
{
public:
~A() = default;
private :
A() = default;
A(const A&) = delete;
A& operator=(const A&) = delete;
template
friend std::unique_ptr make_A(Args&& ...args)
{
return std::unique_ptr(new A(std::forward(args)...));
}
};
Now your clients can obviously get a unique_ptr
:
std::unique_ptr p1 = make_A();
But your clients can just as easily get a shared_ptr
:
std::shared_ptr p2 = make_A();
Because std::shared_ptr
can be constructed from a std::unique_ptr
. And if you have any user-written smart pointers, all they have to do to be interoperable with your system is create a constructor that takes a std::unique_ptr
, just like std::shared_ptr
has, and this is very easy to do:
template
class my_smart_ptr
{
T* ptr_;
public:
my_smart_ptr(std::unique_ptr p)
: ptr_(p.release())
{
}
// ...
};