I was reading through Stroustrup’s C++ (3ed, 1997) to see how he implemented the RAII, and on page 365 I found this:
class File_ptr{
FILE* p;
public:
File_ptr(const char* n, const char* a){p = fopen(n, a);}
File_ptr(FILE* pp) { p = pp; }
~File_ptr() {fclose(p);}
operator FILE* () {return p;}
};
The implementation of constructors and destructors is obvious and complies with the RAII idiom, but I don’t understand why he uses the operator FILE* () {return p;}
.
This would result in using File_ptr
in the following way:
FILE* p = File_ptr("myfile.txt", "r");
The result in a closed p
, which is semantically inappropriate in this case. Also, if File_ptr
is meant to be used as RAII, this operator allows it to be misused like in the example. Or am I missing something?
File_ptr
to functions such asfputs
that accept aFILE *
, not aFile_ptr
. Yes, this definition allows it to be used incorrectly. – Minhminhostd::string
doesn't have anoperator char const*()
. – Zamirunique_ptr
, which is a modern (C++ 11) class with similar semantics. It uses a method calledget()
in this context. – Sacramentalistconst char* val = std::string("blah").c_str()
. – Hephzibah&
-thingy so nice. (see below in Mikhail answer.) – Larrylars