' P '

whatever I will forget

C++ Overloading assignment operator

C++アサインメントのオペレータでさえ、オーバーロードできるんですね。。。
これ使う時がどんなときなのかというと、Shallow copyではなく、Deep copyが必要なとき。
(クラスのメンバにRawポインタがいる場合。デフォルトだとshallow copyになってしまうため)

どうな風にするかというと、下記

//定義
Type &Type::operator=(const Type &rhs);
class Sample{
private:
    char *str;

public:
    Sample();
    //他コンストラクタは省略
    ~Sample();
    //アサインメントオペレーター定義
    Sample &Sample::operator=(const Sample &rhs);
};

//関数ロジック
Sample &Sample::operator=(const Sample &rhs) {
    //渡されたオブジェクトが同じアドレスが確認。同じなら何もせず返却
    if ( this == &rhs ) 
        return *this
    //すでに存在するポインタのheap内のallocationを削除
    delete [] this->str;
    //再度引数の長さ+null terminateでheapにメモリを確保
    str = new char[std::strlen(rhs.str) +1 ];
    std::strcpy(str, rhs.str);
    return *this;
}

int main(){
    //assignment
    s2 = s1;
    //上の行で、下記のようにオーバーロードアサインメントオペレーターが呼ばれる
    s2.operator=(s1);
}

重要なのは、普通にs2 = s1ってやってしまうと、メンバのstrが同じアドレスを参照していまうけど、
上記のようにやれば、アドレスは別々のところを参照するからええねんで!!!って感じと理解しました。