コピーコンストラクタ

当たり前といえば当たり前なんだけど確認。

#include <iostream>
using namespace std;

struct A {
    double x;
    A () : x(0.0) {}
    A (A &a) {
        cout << "copy constructor of A" << endl;
        x = a.x;
    }
    A &operator= (double xx) {
        cout << "operator= of A" << endl;
        x = xx;
    }
};

struct B {
    A a;
};

int main () {
    B b;
    cout << "b.a = 2;" << endl;
    b.a = 2;
    cout << "B bb = b;" << endl;
    B bb = b;
    return 0;
}

実行。vimから直接。

:!g++ %
:!./a.out
b.a = 2;
operator= of A
B bb = b;
copy constructor of A

つまり、デフォルトのコピーコンストラクタはメンバ変数のコピーコンストラクタを呼ぶ。
operator=()は別に必要なかったけど、なんとなく試してみた。

追記

コピーコンストラクタの引数にconst付け忘れてる……でもそれなりに期待通りの結果。
constはコンパイラに対するannotationであって、実行時に関数プロトタイプを見る時点では関係ないのだろうな。