条項45:C++(コンパイラ)は黙って私たちのためにどの関数を完成し、呼び出しますか?

2588 ワード

1,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 member  can't use default assignment operator|
error: non-static const member  can't use default assignment operator|
再引き出し:「reference member」または「const member」を含むclassにassignmentアクションをサポートする場合は、assginment演算子を自分で定義する必要があります.