We can use std::unique_ptr to hold a pointer allocated with malloc which will be freed appropriately.但是,产生的 std::unique_ptr
的大小将是2个指针,一个用于指向对象的指针,一个用于指向删除函数的指针,而不是通常的指向对象的指针和隐式 delete
. 正如一个答案所指出的那样,可以通过编写一个知道正确删除函数的自定义_3009199来避免这种情况 . 可以使用模板参数使该函数知道,以支持任何删除函数,如下所示:
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());
编译的正确演绎指南是什么?
1 回答
为什么要写自己的
unique_ptr
?只需使用带有自定义删除指针的std::unique_ptr
即可 . 使用C 17,这非常简单:或者,正如Yakk建议的那样,更普遍:
这会让你:
当然,你必须实际写
X
,但你没有空间开销 . 为了使用演绎指南完成相同的操作,您需要包装函数删除器以将其提升为模板参数:将使用如下:
我必须更好,你遇到了所有相同的问题导致标准没有
std::unique_ptr
的扣除指南(即:区分指针和数组) . 因人而异 .