C++对象模型 ch5 构造 析构 拷贝语义学

本文深入探讨了拷贝运算符的实现方式,指出其在某些情况下的冗余复制问题,并通过实例解释了构造函数执行流程。同时,文章还讨论了在构造函数成员初始化列表中调用虚函数的安全性和可行性,提供了一个关于虚函数使用的实用指南。

1. 关于拷贝operator

While poking around cfront recently, I noticed that when generating the copy operator, it does not condition the copy by a guard of the form

if ( this == &rhs ) return *this;
As a result, it applies redundant copying for expressions such as

Line *p1 = &a;
Line *p2 = &a;
*p1 = *p2;

2.构造函数做了哪些动作?

The general algorithm of constructor execution is as follows:

1) Within the derived class constructor, all virtual base class and then immediate base class constructors are invoked.

2) That done, the object's vptr(s) are initialized to address the associated virtual table(s).

3) The member initialization list, if present, is expanded within the body of the constructor. This must be done after the vptr is set in case a virtual member function is called.

4) The explicit user-supplied code is executed.

3. 在构造函数成员初始化列表中调用虚函数是不是安全的?
Is it safe to invoke a virtual function of the class within its constructor's member initialization list? Physically, it is always safe when the function is applied to the initialization of a data member of the class. This is because, as we've seen, the vptr is guaranteed to have been set by the compiler prior to the expansion of the member initialization list. It may not be semantically safe, however, because the function itself may depend on members that are not yet initialized. It is not an idiom I recommend. However, from the point of view of the integrity of the vptr, it is a safe operation.

4. 编译器何时生成一个析构函数?

If a destructor is not defined by a class, the compiler synthesizes one only if the class contains either a member or base class with a destructor. Otherwise, the destructor is considered to be trivial and is therefore neither synthesized nor invoked in practice.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值