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