Доступ к неактивному члену объединения — это неопределенное поведение, которое я знаю. Но из этого правила есть одно исключение.
Согласно стандарту C++23 [class.mem.general]/26,
В объединении стандартной компоновки с активным членом (11.5) структурного типа T1 разрешается читать нестатический
элемент данных m другого члена объединения структурного типа T2 при условии, что m часть общей начальной последовательности
Т1 и Т2; поведение такое, как если бы был назначен соответствующий член T1.
Таким образом, согласно стандарту, следующий код имеет четко определенное поведение.
(примечание: следующий код также взят из стандарта)
Код: Выделить всё
struct T1 { int a, b; };
struct T2 { int c; double d; };
union U { T1 t1; T2 t2; };
int f() {
U u = { { 1, 2 } }; // active member is t1
return u.t2.c; // OK, as if u.t1.a were nominated
}
Поэтому я подготовил следующий код
( Вот ссылка на проводник компилятора: https://godbolt.org/z/G4e3avMaz
Код: Выделить всё
#include
template
struct Test_Union {
struct T1 {
T item_1 ;
} ;
struct T2 {
T item_1 ;
} ;
union Union {
T1 t1 ;
T2 t2 ;
} ;
static_assert(std::is_standard_layout_v) ;
static_assert(std::is_standard_layout_v) ;
static_assert(sizeof(T1) == sizeof(T2)) ;
static_assert(sizeof(T1) == sizeof(Union)) ;
static constexpr Union test_1 = {.t1 = {value}} ;
constexpr T no_error_1 (void) {
return test_1.t1.item_1 ;
}
constexpr T no_error_2 (void) {
constexpr Union test_2 = {.t1 = {value}} ;
return test_2.t1.item_1 ;
}
constexpr T error_1 (void) {
return test_1.t2.item_1 ;
}
constexpr T error_2 (void) {
constexpr Union test_2 = {.t1 = {value}} ;
return test_2.t2.item_1 ;
}
} ;
int main (void) {
[]() consteval {
Test_Union test ;
test.no_error_1() ;
} () ;
[]() consteval {
Test_Union test ;
test.no_error_2() ;
} () ;
// consteval function is not a constant expression error
[]() consteval {
Test_Union test ;
test.error_1() ;
} () ;
// consteval function is not a constant expression error
[]() consteval {
Test_Union test ;
test.error_2() ;
} () ;
}
Причины те же.
Для лязга:
Код: Выделить всё
:55:5: error: call to consteval function 'main()::(anonymous class)::operator()' is not a constant expression
55 | []() consteval {
| ^
:35:16: note: read of member 't2' of union with active member 't1' is not allowed in a constant expression
35 | return test_1.t2.item_1 ;
| ^
:57:9: note: in call to 'test.error_1()'
57 | test.error_1() ;
| ^~~~~~~~~~~~~~
:55:5: note: in call to '[]() {
Test_Union test;
test.error_1();
}.operator()()'
55 | []() consteval {
| ^~~~~~~~~~~~~~~~
56 | Test_Union test ;
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
57 | test.error_1() ;
| ~~~~~~~~~~~~~~~~
58 | } () ;
| ~~~~
:60:5: error: call to consteval function 'main()::(anonymous class)::operator()' is not a constant expression
60 | []() consteval {
| ^
:40:16: note: read of member 't2' of union with active member 't1' is not allowed in a constant expression
40 | return test_2.t2.item_1 ;
| ^
:62:9: note: in call to 'test.error_2()'
62 | test.error_2() ;
| ^~~~~~~~~~~~~~
:60:5: note: in call to '[]() {
Test_Union test;
test.error_2();
}.operator()()'
60 | []() consteval {
| ^~~~~~~~~~~~~~~~
61 | Test_Union test ;
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~
62 | test.error_2() ;
| ~~~~~~~~~~~~~~~~
63 | } () ;
Например, доступ к t2.item_1 должен быть таким же, как доступ к t1.item_1.
И что вы думаете?
Я не смог придумать никакого логического ответа, почему компиляторы показывают ошибку.
Единственное, что мне пришло в голову, это то, что это похоже на ошибку компилятора.
Подробнее здесь: https://stackoverflow.com/questions/793 ... ction-caus