0
0

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 3 years have passed since last update.

デフォルトコンストラクタを=default指定した場合の挙動メモ

Last updated at Posted at 2022-05-19

タイトル通り、=defaultでハマったのでメモとして残しておきます。C++20です。

下記のコードは問題なくコンパイルできます。(「フィールドが未初期化である」旨の警告は出ます。)

struct Hoge {
	int a;
	double b;

	Hoge(){}
	Hoge(const int a, const double b):a(a), b(b){}
};

int main() {
	Hoge hoge;
	int c = hoge.a;
	return 0;
}

しかし下記のコードはコンパイルできません。「初期化されていないローカル変数を使用している」旨のコンパイルエラーが発生します。

struct Hoge {
	int a;
	double b;

	Hoge() = default;
	Hoge(const int a, const double b):a(a), b(b){}
};

int main() {
	Hoge hoge; 
	int c = hoge.a;//ここでコンパイルエラー発生。
	return 0;
}
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?