You aren't supposed to create FILE
instances with new
and destroy them with delete
, like make_shared
does. Instead, FILE
s are created with fopen
(or in this case, _wfopen_s
) and destroyed with fclose
. These functions do the allocating and deallocating internally using some unspecified means.
Note that _wfopen_s
does not take a pointer but a pointer to pointer - it changes the pointer you gave it to point to the new FILE
object it allocates. You cannot get the address of the pointer contained in shared_ptr
to form a pointer-to-pointer to it, and this is a very good thing - it would horribly break the ownership semantics of shared_ptr
and lead to memory leaks or worse.
However, you can use shared_ptr
to manage arbitrary "handle"-like types, as it can take a custom deleter object or function:
FILE* tmp;
shared_ptr<FILE> fp;
if(_wfopen_s(&tmp, L"ftest.txt", L"r") == 0) {
// Note that we use the shared_ptr constructor, not make_shared
fp = shared_ptr<FILE>(tmp, std::fclose);
} else {
// Remember to handle errors somehow!
}
Please do take a look at the link @KerrekSB gave, it covers this same idea with more detail.