通过shared_ptr,您可以使用自定义删除器,例如:
auto fp = shared_ptr<FILE>( fopen("file.txt", "rt"), &fclose );
fprintf( fp.get(), "hello\n" );
并且fclose
无论函数如何退出,这都会记住文件。
但是,重新引用一个局部变量似乎有点矫kill过正,所以我想使用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)>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句