ページ 1 / 1
構造体をコンストラクタで初期化した時0クリアされるのでしょうか
Posted: 2013年2月09日(土) 12:24
by 立花希海
こんにちは。
配列などをコンストラクタで初期化すれば全ての要素が0クリアされるとの事ですが
コード:
class CTEST{
public:
char m_cString[ 256 ];
CTEST()
: m_cString()
{}
};
構造体を同様の書式にした時、構造体は0クリアされるのでしょうか
コード:
class CTEST{
public:
struct StTEST
int m_Value;
};
StTEST m_stTest;
CTEST()
: m_stTest()
{}
};
構造体にはコンストラクタを作らない、memsetでクリアしない場合です。
テストした限りでは0になっているのですがたまたまなのか一応初期化されるのか
各要素をコンストラクタで初期化すれば確実なのでしょうけれど仕様的にどうなのか
気になったので質問します。
Re: 構造体をコンストラクタで初期化した時0クリアされるのでしょうか
Posted: 2013年2月09日(土) 13:03
by h2so5
C++の規格上、0で初期化されることになっています。
http://www.open-std.org/jtc1/sc22/wg21/ ... /n1905.pdf
8. An object whose initializer is an empty set of parentheses, i.e., (), shall be value-initialized.
To value-initialize an object of type T means:
— if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called
(and the initialization is ill-formed if T has no accessible default constructor);
— if T is a non-union class type without a user-declared constructor, then every non-static data member and baseclass component of T is value-initialized;
96)
— if T is an array type, then each element is value-initialized;
— otherwise, the object is zero-initialized
Re: 構造体をコンストラクタで初期化した時0クリアされるのでしょうか
Posted: 2013年2月09日(土) 15:39
by 立花希海
なるほど。ありがとうございました!!