假设我有一个名为的类Derived
,该类继承自名为的类Base
。Base
这很特殊-尽管可以使用new创建它,但必须通过自定义删除器对其进行销毁。
我希望将Base
其unique_ptr
与名为的自定义删除器一起使用BaseDeleter
。这也使我可以拥有从其派生的其他类Base
。为了异常安全和一致性,我想使用std::make_unique
来声明我的unique_ptr
。
我创建了一个小片段来演示我想要的内容:
#include <memory>
class Base
{
};
class Derived : public Base
{
};
struct BaseDeleter
{
void operator()(Base* base)
{
// Perform some special deleting
}
};
class Big
{
public:
Big()
{
//pointer.reset(new Derived()); // This works!
pointer = std::make_unique<Derived, BaseDeleter>(); // But this doesn't...
}
private:
std::unique_ptr<Base, BaseDeleter> pointer;
};
int main()
{
Big clazz;
}
不幸的是,这无法在Visual Studio 2015 Update 2和gcc-5.1上进行编译。(ideone)
为什么这不起作用?一个人怎么能std::make_unique
分配这样的std::unique_ptr
?
这是的签名make_unique
之一,我猜您希望使用该签名:
template< class T, class... Args >
unique_ptr<T> make_unique( Args&&... args );
T
您要创建的对象的类型在哪里,您要Args...
转发给构造函数的参数的类型在哪里。
如您所见,您无法使用make_*
智能指针的辅助功能(既不使用make_unique
也不使用make_shared
)来指示自定义删除器。
您必须显式构造指针,如下所示:
std::unique_ptr<T, D> ptr{new T{)};
如果删除程序不是默认可构造的,则可以执行以下操作:
std::unique_ptr<T, D> ptr{new T{}, d};
d
删除程序的实例在哪里。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句