templates - 使用 std::make_shared 拥有自己的 std::shared_ptr

标签 templates c++11 shared-ptr

对于调试情况,我需要实现自己版本的shared_ptr 类。通常,当我使用 std::shared_ptr 时,为了方便起见,我使用 typedef:

typedef std::shared_ptr<myclass> myclassptr;

在调试情况下,我想使用一些额外的调试方法而不是使用 typedef 来扩展 shared_ptr 模板,而不是 myclass 类:

class myclassptr : public std::shared_ptr<myclass>
{
  public:
   // some special tracking methodes
};

但这给我留下了一个无法编译的 Actor :

myclassptr mcp=std::make_shared<myclass>();

我已经将 make_shared 封装在工厂函数中,例如:

myclassptr createMyClass()
{
  return std::make_shared<myclass>();
}

但是我怎样才能获得我的调试版本?

最佳答案

myclassptr一个接受std::shared_ptr的构造函数(也可能还有赋值运算符):

class myclassptr : public std::shared_ptr<myclass>
{
  public:
   // some special tracking methodes

    myclassptr(std::shared_ptr<myclass> arg)
      : std::shared_ptr<myclass>(std::move(arg))
    {}

    myclassptr& operator= (std::shared_ptr<myclass> src)
    {
      std::shared_ptr<myclass>::operator=(std::move(src));
      return *this;
    }
};

根据您使用 myclassptr 的方式,您可能希望也可能不希望将构造函数标记为显式

关于templates - 使用 std::make_shared 拥有自己的 std::shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24322857/

相关文章:

c++ - 如何从(嵌套的)std::initializer_list 确定大小?

c++ - 使用继承的 luabind 和 std::shared_ptr

c++ - 无法推断间接调用模板函数的类型

html - 固定表格中的文本位置

c++ - 模板默认为具有更多模板的模板

c++ - 不可复制但可移动的容器

c++ - 如何在 gdb 中打印 `std::array` 内容?

使用 shared_ptr 的抽象基类的子类的 C++ == 运算符

c++ - 智能指针+循环+ "->"

c++ - Clang 中带有静态 constexpr 的奇怪的循环模板模式 (CRTP)