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

来源:互联网 发布:mmap中文软件 编辑:程序博客网 时间:2024/05/22 08:58

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.

原创粉丝点击