【问题标题】:Own std::shared_ptr with std::make_shared拥有 std::shared_ptr 和 std::make_shared
【发布时间】:2014-08-10 22:49:39
【问题描述】:

对于调试情况,我需要实现自己的 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
};

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

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

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

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

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

【问题讨论】:

  • 有转发到基地的演员吗?
  • @Xeo Uaaa,我忘记了。

标签: templates c++11 shared-ptr


【解决方案1】:

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 的方式,您可能希望也可能不希望将构造函数标记为explicit

【讨论】:

  • 我不得不添加 "*this->get()" 和一些 "" 但我让它在我的 VC C++ 2013 上运行。谢谢
  • @MartinSchlott 抱歉,get() 部分不应该存在,那是我的代码中的“错字”(错误标识符)。它应该返回myclassptr&amp; - 我已经更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
  • 2020-04-26
  • 2016-12-27
  • 1970-01-01
  • 2013-08-20
  • 1970-01-01
相关资源
最近更新 更多