《Effective C++》读书笔记之五 Item 5. Know what functions C++ silently writes and calls.

本文讲解了C++编译器如何为未显式定义构造函数、拷贝构造函数、赋值函数及析构函数的类自动生成默认实现。特别强调了当类包含引用成员或常量成员时,开发者必须自行实现拷贝赋值运算符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本条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. 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值