Size: a a a

2020 March 06

m

magras in pro.cxx
Flower Surgeon
там про УБ вообще ни слова же. От Анатолия я увидел про паддинг, но тут тоже не всё так очевидно. Своими словами можете объяснить, желательно на пальцах?
Вы просите прямо противоположных вещей:
1. Ссылку на стандарт.
2. Чтобы просто на пальцах.

Ссылку на стандарт вам дали.

На пальцах объяснять UB который работает как ожидается на основных платформах? И что вы хотите здесь услышать?
источник
2020 March 07

AB

Artöm Bakri Al-Sarmini in pro.cxx
Artöm Bakri Al-Sarmini
Есть такое понятие, как cis - ряд полей, удовлетворяюших набору требований. Если есть юнион с двумя полями-структурами, и у них есть cis из, скажем, одного инта, этот инт можно читать всегда, независимо от активного поля юниона
union {
   struct {
       int a, b;
   } s1;
   struct {
       int c;
       long d;
       float e;
   } s2;
};
Независимо от того, активно s1 или s2, из a и c можно читать всегда
источник

FS

Flower Surgeon in pro.cxx
Мы не про две структуры, замечу, мы про структуру и массив.
источник

FS

Flower Surgeon in pro.cxx
Именно про конкретный случай.
источник

AB

Artöm Bakri Al-Sarmini in pro.cxx
Artöm Bakri Al-Sarmini
У T и T[N] нет common initial sequence
Поэтому я и написал вот это
источник

FS

Flower Surgeon in pro.cxx
Artöm Bakri Al-Sarmini
union {
   struct {
       int a, b;
   } s1;
   struct {
       int c;
       long d;
       float e;
   } s2;
};
Независимо от того, активно s1 или s2, из a и c можно читать всегда
Ну и да, в структуре поля строго одного типа int.
источник

TS

Till Schneider in pro.cxx
Flower Surgeon
Мы не про две структуры, замечу, мы про структуру и массив.
На cppref есть пример вроде
Где вот объясняется, что делать можно, а что нельзя
источник

P

Pepe 🐸 in pro.cxx
Artöm Bakri Al-Sarmini
Есть такое понятие, как cis - ряд полей, удовлетворяюших набору требований. Если есть юнион с двумя полями-структурами, и у них есть cis из, скажем, одного инта, этот инт можно читать всегда, независимо от активного поля юниона
2051. Simplifying alias rules
Section:
6.10  [basic.lval]     Status: drafting     Submitter: Richard Smith     Date: 2014-12-03
The aliasing rules of 6.10 [basic.lval] paragraph 10 were adapted from C with additions for C++. However, a number of the points either do not apply or are subsumed by other points. For example, the provision for aggregate and union types is needed in C for struct assignment, which in C++ is done via constructors and assignment operators in C++, not by accessing the complete object.
Suggested resolution:
Replace 6.10 [basic.lval] paragraph 10 as follows:
If a program attempts to access the stored value of an object through a glvalue whose type is not similar (7.5 [conv.qual]) to one of the following types the behavior is undefined: [Footnote:... —end footnote]
• the dynamic type of the object,
• the signed or unsigned type corresponding to the dynamic type of the object, or
• a char or unsigned char type.
Additional note, October, 2015:
It has been suggested that the aliasing rules should be extended to permit an object of an enumeration with a fixed underlying type to alias an object with that underlying type.

вот кстати про юнионы
источник

P

Pepe 🐸 in pro.cxx
Pepe 🐸
2051. Simplifying alias rules
Section:
6.10  [basic.lval]     Status: drafting     Submitter: Richard Smith     Date: 2014-12-03
The aliasing rules of 6.10 [basic.lval] paragraph 10 were adapted from C with additions for C++. However, a number of the points either do not apply or are subsumed by other points. For example, the provision for aggregate and union types is needed in C for struct assignment, which in C++ is done via constructors and assignment operators in C++, not by accessing the complete object.
Suggested resolution:
Replace 6.10 [basic.lval] paragraph 10 as follows:
If a program attempts to access the stored value of an object through a glvalue whose type is not similar (7.5 [conv.qual]) to one of the following types the behavior is undefined: [Footnote:... —end footnote]
• the dynamic type of the object,
• the signed or unsigned type corresponding to the dynamic type of the object, or
• a char or unsigned char type.
Additional note, October, 2015:
It has been suggested that the aliasing rules should be extended to permit an object of an enumeration with a fixed underlying type to alias an object with that underlying type.

вот кстати про юнионы
и вот
Notes
The paragraph defining the strict aliasing rule in the standard contains two additional bullets partially inherited from C:
▪ AliasedType is an aggregate type or a union type which holds one of the aforementioned types as an element or non-static member (including, recursively, elements of subaggregates and non-static data members of the contained unions).
▪ AliasedType is a (possibly cv-qualified) base class of DynamicType.
These bullets describe situations that cannot arise in C++ and therefore are omitted from the discussion above. In C, aggregate copy and assignment access the aggregate object as a whole. But in C++ such actions are always performed through a member function call, which accesses the individual subobjects rather than the entire object (or, in the case of unions, copies the object representation, i.e., via unsigned char). See core issue 2051.
источник

FS

Flower Surgeon in pro.cxx
Till Schneider
На cppref есть пример вроде
Где вот объясняется, что делать можно, а что нельзя
Я такого не нашёл. Понимаю, что union — скользкая дорожка, но я не собираюсь рассматривать иные кейсы кроме одного-единственного.
источник

AB

Artöm Bakri Al-Sarmini in pro.cxx
Flower Surgeon
Мы не про две структуры, замечу, мы про структуру и массив.
У T и массива T нет cis. Для меня непонятно, почему первый элемент массива в нее не входит, но стандарт не я писал
источник

TS

Till Schneider in pro.cxx
Flower Surgeon
Я такого не нашёл. Понимаю, что union — скользкая дорожка, но я не собираюсь рассматривать иные кейсы кроме одного-единственного.
https://en.cppreference.com/w/cpp/language/union
Первый же пример кода
источник

P

Pepe 🐸 in pro.cxx
самое смешное вот:

It has been suggested that the aliasing rules should be extended to permit an object of an enumeration with a fixed underlying type to alias an object with that underlying type.

то есть сейчас даже такое нельзя
источник

AB

Artöm Bakri Al-Sarmini in pro.cxx
Там типы разные
источник

TS

Till Schneider in pro.cxx
Artöm Bakri Al-Sarmini
Там типы разные
Там речь о лайфтаймах, неважно же какие типы -_-
источник

FS

Flower Surgeon in pro.cxx
Плохой пример потому, что совсем не тот, что был озвучен изначально.
источник

AB

Artöm Bakri Al-Sarmini in pro.cxx
Till Schneider
Там речь о лайфтаймах, неважно же какие типы -_-
Здесь https://t.me/ProCxx/370506 инициализация s2 не завершает лайфтайм a
источник

FS

Flower Surgeon in pro.cxx
Artöm Bakri Al-Sarmini
У T и массива T нет cis. Для меня непонятно, почему первый элемент массива в нее не входит, но стандарт не я писал
Я жутко извиняюсь за глупый вопрос, но что есть cis в данном контексте?
источник

TS

Till Schneider in pro.cxx
Flower Surgeon
Плохой пример потому, что совсем не тот, что был озвучен изначально.
Как только ты записал во что-то другое, то лайфтайм того объекта заканчивается и начинается лайфтайм этого
источник

AB

Artöm Bakri Al-Sarmini in pro.cxx
Flower Surgeon
Я жутко извиняюсь за глупый вопрос, но что есть cis в данном контексте?
common initial sequence
источник