[Bug c++/80635] std::optional and bogus -Wmaybe-uninitialized warning

palves at redhat dot com gcc-bugzilla@gcc.gnu.org
Wed Dec 18 11:09:00 GMT 2019


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=80635

--- Comment #36 from Pedro Alves <palves at redhat dot com> ---
(In reply to Jason Merrill from comment #33)
> (In reply to Pedro Alves from comment #32)
> > Usually maybe-uninit warnings point to false positives involving scalars,
> > and initializing them is practically free.  But here the size of T may be
> > significant, which could lead to e.g., calling memset in loops.
> 
> Using optional with a large T sounds like a strange choice to me, since it
> means you have to allocate the space even if you don't have a value.

I see it as a perfectly viable approach to avoiding the heap, or avoiding heap
fragmentation and have better cache locality.  For example, instead of:

struct F
{
  A *a = nullptr;
  B* b = nullptr;
};

and then allocating a / b on the heap as separate allocations, with pointer
nullness indicating whether you have the field, you can have:

struct F
{
  ...
  std::optional<A> a;
  std::optional<B> b;
  ...
};

and allocate the whole thing as one block.  gdb's lookup_name_info object uses
this pattern, for example.


More information about the Gcc-bugs mailing list