本条item主要讲解了c++编译器会为每个类创建默认的构造函数,拷贝构造函数,赋值函数和析构函数,如果在定义类的时候没有定义这些函数,编译器就会在需要的时候调用编译器默认创建的函数。
If you don‘t declare them yourself, compilers will declare their own versions of a copy constructor, a copy assignment operator, and a destructor. Furthermore, if you declare no constructors at all, compilers will also declare a default constructor for you.
If you write
class Empty{};
it is essentially the same as if you‘d written this:
class Empty{ public: Empty(){...} Empty(const Empty& rhs){....} Empty& operator=(const Empty& rhs){...} ~Empty(){...} ... }; Empty e1; // call default constructor; Empty e2(e1); // call copy constructor; e1 = e2; // call copy assignment operator;
If you class constains reference member or const data, you need to write copy assignment by self.
If you want to support assignment in a class containing a reference member, you must define the copy assignment operator yourself. Compilers behave similarly for classes containing const members
(such as objectValue in the modified class above). It‘s not legal to modify const members, so compilers are unsure how to treat them during an implicitly generated assignment function.
Things To Remember:
- Compilers may implicitly generate a class‘s default constructor, copy constructor, copy assignment operator, and destructor.
《Effective C++》读书笔记之五 Item 5. Know what functions C++ silently writes and calls.,布布扣,bubuko.com
《Effective C++》读书笔记之五 Item 5. Know what functions C++ silently writes and calls.