Zero-cost properties with data member syntax

前端 未结 2 1950
旧时难觅i
旧时难觅i 2021-02-12 21:25

I have (re?)invented this approach to zero-cost properties with data member syntax. By this I mean that the user can write:

some_struct.some_member = var;
var =          


        
2条回答
  •  鱼传尺愫
    2021-02-12 22:07

    Here is what the common-initial-sequence rule says about unions:

    In a standard-layout union with an active member of struct type T1, it is permitted to read a non-static data member m of another union member of struct type T2 provided m is part of the common initial sequence of T1 and T2; the behavior is as if the corresponding member of T1 were nominated.

    Your code does not qualify. Why? Because you are not reading from "another union member". You are doing m.x = 42;. That isn't reading; that's calling a member function of another union member.

    So it doesn't qualify for the common initial sequence rule. And without the common-initial-sequence rule to protect you, accessing non-active members of the union is UB.

提交回复
热议问题