Structuring and reinterpreting types

Suppose I have two types A and B.

Then i do this type

struct Pair{
    A a;
    B b;
};

Now I have such a function.

void function(Pair& pair);

And let's assume that functiononly part of the apair will be used .

Then is undefined behavior used and calls the function this way?

A a;
function(reinterpret_cast<Pair&>(a));

I know that the compiler can insert padding bytes after a member, but can it also do this before the first member?

+4
source share
2 answers

I think he defined the behavior, assuming it Pairis a standard layout. Otherwise, this behavior is undefined.

-, . [basic.compound] ( ) :

a b , : * [...]
* , , , [...]
* [...]
, , reinterpret_cast (5.2.10).

[class.mem]:

, . ( ).

, reinterpret_cast A Pair . function - A, , A 0, , function A& . b undefined, .


, , , . , - - function pair.b, . :

void function(A& a) { ... }
void function(Pair& p) { function(p.a); }

function A.

+4

, undefined.

a b. . , .a , , , , , .

-1

Source: https://habr.com/ru/post/1655221/


All Articles