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

constexpr + union + コンストラクタ

Posted at

constexpr で扱えて,実行時の効率もよいデータ構造+アルゴリズム を見て
これは良いと早速使ってみたが、どうも挙動がおかしい。

と思ったらどうやらVC++のバグっぽい。

# include <iostream>
# include <string>
# include <array>

using namespace std;

struct address1 {
	int a;
};

struct address4 {
	unsigned int a1:8;
	unsigned int a2:8;
	unsigned int a3:8;
	unsigned int a4:8;
};
ostream& operator<<(ostream& stream, const address4& a) {
    return stream << a.a1 << "." << a.a2 << "." << a.a3 << "." << a.a4;
}

union X1 {
	address1 a;
	address4 b;
	int c;
};

union X2 {
	int a;
	address4 b;
	int c;
};

static constexpr int initial = 0x0100007f;
constexpr X1 x1_global {{initial}};
constexpr X2 x2_global {initial};
const X1 x1_global_nonexpr {{initial}};
const X2 x2_global_nonexpr {initial};

int main() {
	static constexpr X1 x1_static {{initial}};
	static constexpr X2 x2_static {initial};
	static const X1 x1_static_nonexpr {{initial}};
	static const X2 x2_static_nonexpr {initial};
	constexpr X1 x1_local {{initial}};
	constexpr X2 x2_local {initial};
	const X1 x1_local_nonexpr {{initial}};
	const X2 x2_local_nonexpr {initial};
# define TEST(v) 	cout << __FILE__ "(" << __LINE__ << "): " #v ": " << v.b << endl;
	TEST(x1_global)
	TEST(x2_global)
	TEST(x1_global_nonexpr)
	TEST(x2_global_nonexpr)
	TEST(x1_static)
	TEST(x2_static)
	TEST(x1_static_nonexpr)
	TEST(x2_static_nonexpr)
	TEST(x1_local)
	TEST(x2_local)
	TEST(x1_local_nonexpr)
	TEST(x2_local_nonexpr)
}

実行結果

> cl /nologo /Ob1 /Oi /GS /Gy /GL /GA /RTCu /Zc:inline /EHsc /W3 /WX /MT prog.cpp
prog.cpp
コード生成しています。
コード生成が終了しました。
> prog.cpp.exe
prog.cpp(49): x1_global: 0.0.0.0
prog.cpp(50): x2_global: 127.0.0.1
prog.cpp(51): x1_global_nonexpr: 127.0.0.1
prog.cpp(52): x2_global_nonexpr: 127.0.0.1
prog.cpp(53): x1_static: 0.0.0.0
prog.cpp(54): x2_static: 127.0.0.1
prog.cpp(55): x1_static_nonexpr: 127.0.0.1
prog.cpp(56): x2_static_nonexpr: 127.0.0.1
prog.cpp(57): x1_local: 127.0.0.1
prog.cpp(58): x2_local: 127.0.0.1
prog.cpp(59): x1_local_nonexpr: 127.0.0.1
prog.cpp(60): x2_local_nonexpr: 127.0.0.1

gccでの結果は [Wandbox]三へ( へ՞ਊ ՞)へ ハッハッ を見てほしい。

どうもグローバルもしくはスタティックでconstexprでunionでunionの最初の要素がクラスだと、
コンストラクタが呼ばれないっぽい。

変換テーブルの初期化に使える!って思ったのになぁ…(´・ω・`)

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?