9
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C++ のメンバ変数である配列をコンストラクタで初期化する

Posted at

状況

こんな感じのクラスがある。

class foo
{
public:
    int ary_[3];
    foo();
};

まあ、生の配列使わずに std::array (のようなもの)を使おうよとか思うところはあるけれど、とにかくこういうクラスがある。

で。
デフォルトコンストラクタで ary_ の値を 11,222,3333 で初期化したい。

C++03 の場合

C++03 の場合、わりとどうしようもない。
私なら以下のようにするかな:

C++03
foo::foo()
{
    ary_[0] = 11;
    ary_[1] = 222;
    ary_[2] = 3333;
}

要素数が少なければ代入文をたくさん書くのもありだと思う。
代入文をたくさん書きたくない場合はこう:

C++03
# include <algorithm>

# define STATIC_ASSERT(key, x) enum \
{                                  \
    key = 1 / ((x) ? 1 : 0)        \
};

# define COUNTOF(x) (sizeof(x) / sizeof(*(x)))

template <typename T, size_t size>
inline T *endof(T (&ary)[size])
{
    return ary + size;
}

foo::foo()
{
    int initial_values[] = {11, 222, 333};
    STATIC_ASSERT(array_count_should_be_same, COUNTOF(initial_values) == COUNTOF(ary_));
    std::copy(initial_values, endof(initial_values), ary_);
}

STATIC_ASSERT とか endof は、C++03 で仕事するなら似たようなものをみんな用意していたんじゃないかと思うけどどうだろう。

いずれにせよ。

  1. メンバ変数として、配列の中身がある状態が用意される
  2. そこに何らかの方法で代入される

という流れになるので、配列の要素型にコンストラクタやデストラクタがある場合、無駄な処理が走ってしまう。

C++11 以降の場合

C++03 までの、メンバである配列を初期化するいい方法がない、という欠陥は修正されている。

こんな感じ:

C++11
foo::foo()
    : ary_{11, 222, 3333} {}

ありがたい。

9
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?