Medium
RAII file handle passed by value
What happens when this program runs?
main.cpp
class FileHandle {
public:
explicit FileHandle(const char* path) : fp_(std::fopen(path, "r")) {}
~FileHandle() { if (fp_) std::fclose(fp_); }
// no copy constructor / copy assignment declared -- compiler generates
// a shallow member-wise copy of fp_ (a raw FILE*)
private:
FILE* fp_;
};
void process(FileHandle fh) { // taken by value -- triggers a copy
// use fh...
}
int main() {
FileHandle original("data.txt");
process(original); // copies original; both now share the same FILE*
} // process's fh destructs (fclose), then original destructs (fclose again)108 of 117 in C++