如何只为类强制智能指针实例? [英] How to force only smart pointers instance for a class?

查看:81
本文介绍了如何只为类强制智能指针实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力防止用户使用没有智能指针的类。因此,强制它们具有由智能指针分配和管理的对象堆。
为了获得这样的结果,我尝试了以下操作:

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>;
};

如果您只希望您的班级用户能够通过 std :: unique_ptr 。但是对于 std :: shared_ptr 无效。因此,我想知道您是否有任何想法可以做到这一点。我发现的唯一解决方案是执行以下操作(使用 friend std :: allocator_traits< 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.

推荐答案

创建一个朋友的工厂函数,该函数返回 std :: unique_ptr< A> ,并使您的类没有可访问的构造函数。但要使用析构函数:

Create a friend'd factory function that returns a std::unique_ptr<A>, and make your class have no accessible constructors. But make the destructor available:

#include <memory>

class A;

template <class ...Args>
std::unique_ptr<A> make_A(Args&& ...args);

class A
{
public:
    ~A() = default;
private :
    A() = default;
    A(const A&) = delete;
    A& operator=(const A&) = delete;

    template <class ...Args>
    friend std::unique_ptr<A> make_A(Args&& ...args)
    {
        return std::unique_ptr<A>(new A(std::forward<Args>(args)...));
    }
};

现在,您的客户显然可以获得 unique_ptr< A>

Now your clients can obviously get a unique_ptr<A>:

std::unique_ptr<A> p1 = make_A();

但是您的客户也可以轻松获得 shared_ptr< A>

But your clients can just as easily get a shared_ptr<A>:

std::shared_ptr<A> p2 = make_A();

因为可以构造 std :: shared_ptr 来自 std :: unique_ptr 。并且,如果您有任何用户编写的智能指针,则它们与系统可互操作所需要做的就是创建一个构造器,该构造器使用 std :: unique_ptr ,就像 std :: shared_ptr 拥有,而且很容易做到:

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 T>
class my_smart_ptr
{
    T* ptr_;
public:
    my_smart_ptr(std::unique_ptr<T> p)
        : ptr_(p.release())
    {
    }
    // ...
};

这篇关于如何只为类强制智能指针实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆