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 order to get such a result, I've tried the following :
#include <memory>
class A
{
private :
~A {}
// To force use of A only with std::unique_ptr
friend std::default_delete<A>;
};
This work pretty well if you only want your class users being capable of manipulating instance of your class through std::unique_ptr
. But it doesn't work for std::shared_ptr
. So I'd like to know if you had any ideas to get such a behavior. The only solution that I've found is doing the following (using friend std::allocator_traits<A>;
was unsufficient) :
#include <memory>
class A
{
private :
~A {}
// For std::shared_ptr use with g++
friend __gnu_cxx::new_allocator<A>;
};
But this solution is not portable. Maybe I'm doing it the wrong way.