Passing reference of packed struct member to template. gcc bug?

后端 未结 1 932
忘了有多久
忘了有多久 2021-01-03 00:24

I encountered a problem, passing struct member to a template function. The function\'s goal is to take the address and size of the member. Here is simple example:

Th

1条回答
  •  囚心锁ツ
    2021-01-03 01:00

    Both of your questions are answered at the link you posted.

    1. Why cannot packed-struct members be passed as const references, when their address can be passed as pointer

    Gabriel M. Beddingfield wrote in his comment:

    All assignments of obj.s to type short& and short* are incorrect, and ideally they would all result in compiler errors.

    The C++ spec (C++03, Sects. 3.9, 3.9.1, 3.9.2) are very clear that T and "pointer to T" have implementation-specific alignment requirements. If you have a "pointer to T" then you may assume that it meets the alignment requirements. I'm sure the C spec has similar language.

    I can only add to this the corresponding quote from C++14 standard ([basic.align]/1):

    Object types have alignment requirements (3.9.1, 3.9.2) which place restrictions on the addresses at which an object of that type may be allocated. An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated. An object type imposes an alignment requirement on every object of that type; stricter alignment can be requested using the alignment specifier

    The bottom line of it is that even taking an addres of a packed struct member should be an error.

    2. What happens in the const T& case? There is no error, no warning, but the incorrect address is passed to the function. As we know, the address of reference is the address of the variable, the reference points to.

    Jonathan Wakely wrote:

    A const-reference causes a temporary to be created, you didn't bind to the packed field


    The bottom line is that it's not a bug itself that you can't bind a non-const reference to a packed struct field, a bug is that at the same time you can take an address of it. The compiler should either allow or disallow both.

    0 讨论(0)
提交回复
热议问题