【发布时间】:2017-08-22 20:12:11
【问题描述】:
We can use std::unique_ptr to hold a pointer allocated with malloc which will be freed appropriately.
但是,生成的std::unique_ptr 的大小将是 2 个指针,一个用于指向对象的指针,一个用于指向删除函数的指针,而不是通常的 1 个指向对象的指针和一个隐式的 delete。正如一个答案指出的那样,可以通过编写一个知道正确删除函数的自定义Unique_ptr 来避免这种情况。这个函数可以使用模板参数来支持任何删除函数,如下所示:
template <class T, void (*Deleter)(T *)>
struct Unique_ptr {
explicit Unique_ptr(T *t, void (*)(T *))
: t{t} {}
~Unique_ptr() {
Deleter(t);
}
//TODO: add code to make it behave like std::unique_ptr
private:
T *t{};
};
template <class T>
void free(T *t) {
std::free(t);
}
char *some_C_function() {
return (char *)malloc(42);
}
int main() {
Unique_ptr<char, free> p(some_C_function(), free); //fine
Unique_ptr q(some_C_function(), free); //should be fine
//with the right
//deduction guide
}
如果我们可以使用推导指南而不必指定模板参数,那就太好了。不幸的是,我似乎无法正确使用语法。这些尝试编译失败:
template <class T, auto Deleter>
Unique_ptr(T *, Deleter)->Unique_ptr<T, Deleter>;
template <class T, void (*Deleter)(T *)>
Unique_ptr(T *, void (*Deleter)(T *))->Unique_ptr<T, Deleter>;
也可以编写Unique_ptr<free> q(some_C_function()); 来手动指定函数模板参数,但这会在推导T 时产生问题。
编译Unique_ptr q(some_C_function(), free);或Unique_ptr<free> q(some_C_function());的正确演绎指南是什么?
【问题讨论】:
-
您的唯一指针是否支持数组?如果是,那么你真的不想想要一个演绎指南(无法区分来自
new T()和new T[n]的指针) -
std::unique_ptr通常在删除器为std::default_delete时通过特殊化实现。不会有任何开销。
标签: c++ templates c++17 template-argument-deduction