FILE*
written in C ++ 98: class File { FILE* handle; public: File(const char* filename) { if ( !(handle = fopen(filename, "r")) ) throw std::runtime_error("blah blah blah"); } ~File() { if (handle) fclose(handle); } // ... private: File(const File&); // void operator=(const File&); // };
FILE*
would require some platform-dependent tweaks, and does not have a special physical meaning at all.File
? Unfortunately, we cannot use File
in a standard container, that is, such code simply does not compile: std::vector<File> files; files.push_back(File("data.txt"));
shared_ptr
: std::vector<boost::shared_ptr<File> > files; files.push_back(boost::shared_ptr<File>(new File("data.txt")) );
File
class in C ++ 11: class File { FILE* handle; public: File(const char* filename) { if ( !(handle = fopen(filename, "r")) ) throw std::runtime_error("blah blah blah"); } ~File() { if (handle) fclose(handle); } File(File&& that) { handle = that.handle; that.handle = nullptr; } File& operator=(File&& that) { std::swap(handle, that.handle); return *this; } File(const File&) = delete; // void operator=(const File&) = delete; // // ... };
std::vector<File> files; files.push_back(File("data1.txt")); files.push_back(File("data2.txt")); files.erase(files.begin());
emplace_back
appeared in the containers, which allows you to create an object directly in the container without copying it: std::vector<File> files; files.emplace_back("data1.txt"); // File("data1.txt")
Source: https://habr.com/ru/post/174019/
All Articles