std:vec for classes with constructor?

Jonathan Wakely jwakely@redhat.com
Fri Aug 7 09:17:29 GMT 2020


On 07/08/20 10:55 +0200, Jakub Jelinek wrote:
>On Fri, Aug 07, 2020 at 09:34:38AM +0100, Jonathan Wakely via Gcc-patches wrote:
>> > Now that you say it, vec has a T[1] member so depending on T
>> > there might be a side-effect as invoking its CTOR?  Or it might
>> > even not compile if there is no default CTOR available...  Ick :/
>>
>> Right.
>>
>> Does the GTY stuff add members to the struct, or otherwise alter its
>> layout?
>
>Or perhaps use offsetof on an alternate structure that should have the same
>layout.

Yes that's what I was going to suggest next.

>So instead of
>  typedef vec<T, A, vl_embed> vec_embedded;
>  return offsetof (vec_embedded, m_vecdata) + alloc * sizeof (T);
>use
>  struct alignas (T) U { char data[sizeof (T)]; };
>  typedef vec<U, A, vl_embed> vec_embedded;

static_assert(sizeof(vec_embedded) == sizeof(vec), "");
static_assert(alignof(vec_embedded) == alignof(vec), "");

>  return offsetof (vec_embedded, m_vecdata) + alloc * sizeof (T);
>where vec_embedded should have the same offset of m_vecdata as vec.



More information about the Gcc-patches mailing list