effective c++條款12

1.Copying函數應該確保複製“對象內的所有成員變量”及所有”base class”成分
2.不要嘗試以一個copying函數去實現另一個copying函數,應該將共同機能放進第三個函數中,由兩個copying函數調用

如果類中沒有定義複製構造函數和賦值構造函數,編譯器會爲我們提供默認的賦值和複製構造函數,但是如果你自己定義了這些函數,
但是數據沒有全部copy,編譯器是不會提醒你的

看下面的代碼
假設我們爲了描述一個顧客,定義了以下類

class Customer
{
    public:
    ...
    Customer(const Customer& rhs):m_name(rhs.m_name){}
    Customer& operator=(const Customer& rhs)
    {
        name=rhs.name;
        return *this;
    }
    ...
    private:
    std::string m_name;
}

上面的代碼是OK的沒有問題的,但是如果在類中添加了一個成員變量Data RegTime(註冊時間),如果不對前面的代碼加以修改,編譯器和鏈接器也是不會報錯的,這就很嚴重了

如果發生繼承,可能會發生更加嚴重的問題
我們相對客戶的優先級(星級)進行分類

class PriorityCustomer:pulic Customer
{
    public:
    ...
    PriorityCustomer(const PriorityCustomer& rhs):m_priority(rhs.m_priority)
    {

    }

    PriorityCustomer& operator=(const PriorityCustomer& rhs)
    {
        m_priority=rhs.m_priority;
        return *this;
    }
    ...
    private:
    int m_priority;
}

這樣的代碼看起來沒有問題,但是,卻忽略了baseclass的成分
所以正確的寫法是

class PriorityCustomer:pulic Customer
{
    public:
    ...
    PriorityCustomer(const PriorityCustomer& rhs):Customer(rhs),m_priority(rhs.m_priority)
    {

    }

    PriorityCustomer& operator=(const PriorityCustomer& rhs)
    {
        Customer::operator=(rhs);
        m_priority=rhs.m_priority;
        return *this;
    }
    ...
    private:
    int m_priority;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章