使用带有UNIQUE_PTR的自定义删除程序自定义、程序、UNIQUE_PTR

2023-09-03 13:14:02 作者:Enterゝ

通过SHARED_PTR,您可以使用自定义删除器,如:

auto fp = shared_ptr<FILE>( fopen("file.txt", "rt"), &fclose );
fprintf( fp.get(), "hello
" );

并且无论函数如何退出,它都会记住fclose文件。 但是,重新计算局部变量似乎有点过分,所以我想使用unique_ptr

auto fp = unique_ptr<FILE>( fopen("file.txt", "rt"), &fclose );
删除的聊天记录,通过电脑能不能再查出来

但是,这不能编译。

这是缺陷吗?有没有简单的变通办法?我错过了一些琐碎的东西吗?

推荐答案

unique_ptr<FILE, int(*)(FILE*)>(fopen("file.txt", "rt"), &fclose);

自http://en.cppreference.com/w/cpp/memory/unique_ptr

或者,因为您使用的是C++11,所以可以使用decltype

std::unique_ptr<FILE, decltype(&fclose)>