new 配列の初期化

new で配列確保と同時に初期化ってできなかったっけ ? と思って調べてみたら default constructor をもっている class type や arithmetic, enumeration, pointer, pointer-to-member type なら以下のように書くことができるらしい。

class bullet {};

int main(void) {
    const unsigned int MAGAZINE_MAX = 100;
    const unsigned int BUF_SIZE = 0xffff;

    // initialize 100 bullets with the default constructor bullet()
    bullet* bullets = new bullet[MAGAZINE_MAX]();
    // initialize a buffer with the default constructor char():
    // buf is filled with zero
    char* buf = new char[BUF_SIZE]();

    delete[] bullets;
    delete[] buf;

    return 0;
}

元ネタは以下。 default constructor は呼べるけど引数のある constructor は呼べないらしい。 arithmetic type とかだと 0 初期化で固定。期待させんなー。

ここらへんに関連する記述がないか C++98 の仕様も見てみたんだけど BNF だけ読むと new-initializer の中に式があってもいいように解釈できるんだよね…。他のところにここらへんの条件が書いてあるのかもしれないんだけどヨモギ花粉にやられてるのであまり深くつっこまないことにした。

new-expression:
::opt new new-placementopt new-type-id new-initializeropt
::opt new new-placementopt ( type-id ) new-initializeropt
new-placement:
( expression-list )
new-type-id:
type-specifier-seq new-declaratoropt
new-declarator:
ptr-operator new-declaratoropt
direct-new-declarator
direct-new-declarator:
[ expression ]
direct-new-declarator [ constant-expression ]
new-initializer:
( expression-listopt )

http://www.kuzbass.ru:8086/docs/isocpp/expr.html#expr.new