多くのデータ メンバーを持つクラスA
があり、そのうちのいくつかは定数です。すべてのデータ メンバーには適切なコピー コンストラクターがあるため、クラスのコピー コンストラクターをデフォルトに設定します。
class A
{
public:
A() : a(1) {}
A(const A& op) = default;
private:
// ... Lots of constant and non-constant member data ...
const int a;
};
A
次に、定数データ メンバーの 1 つを初期化する値への参照と値を受け入れるコンストラクターを作成します。
A(const A& op, const int a_);
ここop
にコピーする必要があり、その後またはコピーの代わりにa
初期化する必要があります。a_
コピー コンストラクターに委譲してすべてのデータ メンバーを手動で初期化することは避けたいのですが、この場合、const データ メンバーを上書きするにはどうすればよいですか? 例えば:
// Illegal: constructor delegation can't be mixed with field initialization.
A(const A& op, const int a_) : A(op), a(a_) {}
// Illegal: attempt to assign constant member.
A(const A& op, const int a_) : A(op) { a = a_; }
// Hack. May lead to UB in some cases.
A(const A& op, const int a_) : A(op)
{
*(const_cast<int*>(&a)) = a_;
// ... or same tricks with memcpy ...
}
a
明らかに、これらのアプローチはすべて、初期化を2 回試みるため、悪です。
別の解決策は、すべての定数データを基本クラスに移動し、必要なすべての ctor を書き込むことですが、冗長に見えます。
実装するためのよりクリーンな方法はありA(const A&, int a_)
ますか?