5

デフォルト ctor の独自の定義内で集約の初期化を呼び出すことは可能ですか?

GCC は、次のコードで「エラー: コンストラクターがそれ自体に委任されています」と文句を言います。

struct X {
  int x, y, z, p, q, r;
  X(): x{}, y{}, z{}, p{}, q{}, r{} { }  // cumbersome
//X(): X{} { }  // the idea is nice but doesn't compile
};

memset(this, 0, sizeof(*this))現在ctor本体で使用しています。

4

3 に答える 3

0

これには CRTP を使用できます。

template<class C>
struct ZeroInitialized
{
    ZeroInitialized() { memset((C*)this, 0, sizeof(C)); }
};


struct A : ZeroInitialized<A>
{
    int x, y, z, p, q, r;
};

しかし、これが安全であることを保証するものではありません。

于 2016-06-02T13:42:57.010 に答える
0

ファクトリ パターンを使用- コンストラクターの本体を別のクラスに移動します。

struct X {
  int x, y, z, p, q, r;
};

struct XFactory {
  X create();
};

X XFactory::create()
{
   X x{};
   // do needed modification
   return x;
}

私は常にファクトリーパターンを好みますが、明示的なニーズに合わせて他の方法もあります-メンバーデータごとにデフォルトのコンストラクターを定義します。

template <typename T>
struct DefaultConstructibleData
{
   T data;
   DefaultConstructibleData() data{} {} 
};

そしてそれを使用します:

struct X {
  DefaultConstructibleData<int> x, y, z, p, q, r;
  X() 
  {         
       // do whatever you needs to do
       // all x,y,... are already constructed to their defaults
  }
};
于 2016-06-02T14:00:50.757 に答える