Considering this as an intellectual exercise in which you do not want to use std::vector , you need to separate your classes so that they have one responsibility. Here is my class "integer array". Its task is to manage memory for an integer array.
class IntArray { public: IntArray() : ptr_(new int[100]) {} ~IntArray() { delete[] ptr_; } IntArray(const IntArray&) = delete;
Here is my file handling class. His responsibility is to manage FILE* .
class FileHandle { public: FileHandle(const char* name, const char* mode) : fp_(fopen(name, mode)) { if (fp_ == 0) throw std::runtime_error("Failed to open file"); } ~FileHandle() { fclose(fp_);
Note that I am converting my build error to an exception; fp_ , which is a valid file pointer, is an invariant that I want to support, so I abort the construction if I cannot set this invariant.
Now making File_ptr exception File_ptr easy, and the class does not require complex resource management.
class File_ptr { private: FileHandle p; IntArray i; public: File_ptr(const char* n, const char* s) : p(n, s) , i() {} };
Note the absence of any user-declared destructor, copy assignment operator, or copy constructor. I can change the order of the members, and in any case, it doesn't matter which constructor throws.
Charles Bailey
source share