繁体   English   中英

unique_ptr 和 make_unique 中的自动模板参数推导

[英]Automatic template parameter deduction in unique_ptr and make_unique

如果我直接调用 class 构造函数但我没有在std::unique_ptrstd::make_unique中得到它,为什么会得到自动模板参数扣除? 这是一个例子:

#include <memory>
template <class T>
class C
{
public:
 C(const T * const t_) : t(t_) {}
 ~C(void) { delete t; }
private:
 const T * const t;
};

示例 1(作品):

int main(void)
{
 const int * const t = new int;
 auto * const c = new C(t);
 return 0;
}

示例 2(不编译):

int main(void)
{
 const int * const t = new int;
 auto * const c = new C(t);
 std::unique_ptr p(c); // class template argument deduction failed
 return 0;
}

示例 3(作品):

int main(void)
{
 const int * const t = new int;
 const auto c = std::make_unique<C<int>>(t);
 return 0;
}

示例 4(不编译):

int main(void)
{
 const int * const t = new int;

 // no matching function for call to ‘make_unique<template<class T> class C>(const int* const&)
 const auto c = std::make_unique<C>(t);
 return 0;
}

代码使用g++ -std=c++17 (gcc-11.2.0) 编译。

示例 2 和示例 4 中的问题是什么? 如何修复它们?

非常感谢您的帮助!

在 #2 中,故意为std::unique_ptr禁用CTAD 以避免std::unique_ptr(new T[10])的问题,它看起来就像std::unique_ptr(new T)但需要delete[]而不是delete .

在 #4 中,该语言根本不支持这一点:无法将任何class 模板作为模板参数传递,以便基于 function arguments 内部的 std_make_unique 执行std::make_unique (可以通过具有特定(元)签名的 class 模板,但这不适用于一般设施。)

这是解决它的一种方法:

template <class T>
auto MakeUnique(T t) 
{ return std::unique_ptr<std::remove_reference_t<decltype(*t)>>(t); }

int main(void)
{
 const int * const t = new int;
 auto * const c = new C(t);
 auto p = MakeUnique(c);
 return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM