All notes are my personal thoughts on the Book Effective C++ Third Edition by Scott Meyers. They do not represent the opinions of any affiliations.
Use Object to Manage Memory
The part primarily talks about the advantage of using objects as a tool for managing memory. Except for RAII, the usage of destructor to release resources is an important part. Consider the following code:
class Database{ public: // Some basic function void closeConnection(); ~Database(){ if(!is_connection_closed){ closeConnection(); } } private: bool is_connection_closed; }
The destructor takes the charge of closing the necessary connection when the object is deleted. This is similar to the idea of lock_guard in the <mutex>, which uses a struct to handle necessary unlock.
Moreover, the book talks about the importance of managing the copying behavior in such objects. Should copying be prohibited? Or, should resources be transferred? Or, should resource be held and return objects that save references?
Each Object should also provide some access to raw pointers. There are two ways: explicit and implicit conversions. The following code illustrates two ways.
class RealNumber{ public: // Some basic function float get() const{ return x; } // Explicit Conversion operator float() const { return x; } // Implicit Conversion private: float x; }
Use the same form of new and delete operators
This part primarily deals with the usage of different operators between pointers and arrays. The coder should always delete a pointer with normal delete and array with array delete. The reason for this is because arrays are coded with a variable in the front of the memory address that denote the length of the array. It was also suggested that do not use typedef for arrays because it may confuse the users.
int *ptr_x; int arr_x[100]; delete ptr_x; // OK delete [] arr_x; // OK delete arr_x; // Error!
The last part of this chapter talks about something that is related to the smart pointer. Since C++ standard has been renewed, I will talk about this later when writing a note for modern C++. 🙂