Using custom delete with unique_ptr

With shared_ptr, you can use a custom div, for example:

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

and this will remember the fclose file no matter how the function exits.
However, it seems a bit overkill to recount the local variable, so I want to use unique_ptr :

 auto fp = unique_ptr<FILE>( fopen("file.txt", "rt"), &fclose ); 

however, this does not compile.

Is this a defect? Is there an easy way? Am I missing something trivial?

+7
c ++ smart-pointers
source share
1 answer

Must be

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

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

or, since you are using C ++ 11, you can use decltype

 std::unique_ptr<FILE, decltype(&fclose)> 
+11
source share

All Articles