kmplayer 发表于 2013-2-4 22:50:27

条款45:C++(编译器)默默为我们完成和调用哪些函数

1,一个空的class何时不为空?
当C++编译器处理过它们之后.
2,如果你这么写:
class Empty{};
其意义相当于:
class Empty
{
public:
Empty();
Empty(const Empty& rhs);
~Empty();

Empty& operator=(cosnt Empty& rhs);
Emtpy* opertor&();
const Empty* operator&() const;
};

3,需要注意的是:
只有当这些函数被需要时,编译器才会定义它们.
如:
const Empty e1;                     // default constructor;
                                    // destructor
Empty e2(e1);                     // copy constructor
e2 = e1;                            // assignment operator
Empty *pe2 = &e2;                   // address-of
                                    // operator (non-const)
const Empty *pe1 = &e1;             // address-of
                                    // operator (const)
注意:产生出来的destructor并非虚拟函数,除非这个class继承自一个base class,而该base class拥有一个virtual destructor.
这些函数实际被定义成这样:
inline Empty::Emtpy(){}
inline Empty::~Emtpy(){}
inline Empty* Empty::operator&(){ return this; }
inline const Empty* Empty::operator&() const { return this; }

4,对于copy constructor或assignment运算符,官方规则是:
缺省的copy constructor(或assignment)对class的nonstatic data members执行memberwise copy constructor.
如果m是class C中的一个型别T的nonstatic data member,而c没有声明copy constructor或assignment,那么就调用T的copy constructor或assignment,知道遇到一个copy constructor或assignment或是遇上内建型别(如int,double).
缺省情况下,内建型别以bitwise copy方式进行copy constructor或assignment.

5,考虑下面的例子:
#include<iostream>using namespace std;template<class T>class NamedObject{public:    NamedObject(string& name, const T& value):nameValue(name),objectValue(value){};private:    string& nameValue;    const T objectValue;};int main(){    string newDog("Persephone");    string oldDog("Satch");    NamedObject<int> p(newDog, 2);    NamedObject<int> s(oldDog, 29);    p = s;    return 0;}
p中的data members将如何变动?
C++决定拒绝这份代码.
编译错误:
error: non-static reference membercan't use default assignment operator|
error: non-static const membercan't use default assignment operator|

再次引出:如果你打算让一个内含"reference member"或"const member"的class支持assignment动作,你必须自己定义assginment运算符.
页: [1]
查看完整版本: 条款45:C++(编译器)默默为我们完成和调用哪些函数