How to get around GCC ‘*((void*)& b +4)’ may be used uninitialized in this function warning while using boost::optional

There are two levels of uninitialized analysis in gcc:

  • -Wuninitialized: flags variables that are certainly used uninitialized
  • -Wmaybe-uninitialized: flags variables that are potentially used uninitialized

In gcc (*), -Wall turns on both levels even though the latter has spurious warnings because the analysis is imperfect. Spurious warnings are a plague, so the simplest way to avoid them is to pass -Wno-maybe-uninitialized (after -Wall).

If you still want the warnings, but not have them cause build failure (through -Werror) you can white list them using -Wno-error=maybe-uninitialized.

(*) Clang does not activate -Wmaybe-uninitialized by default precisely because it's very imprecise and has a good number of false positives; I wish gcc followed this guideline too.


I have found that changing the construction of b into the following (effectively equal) code:

auto b = boost::make_optional(false,0);

eliminates the warning. However, the following code (which is also effectively equal):

boost::optional<int> b(false,0);

does not eliminate the warning. It's still a little unsatisfactory...


Had the same issue with this piece of code:

void MyClass::func( bool repaint, bool cond )
{
    boost::optional<int> old = m_sizeLimit; // m_sizeLimit is a boost::optional<int> class attribute

    if ( cond )
        m_sizeLimit = 60;
    else
        m_sizeLimit.reset();

    if ( repaint )
    {
        if ( old != m_sizeLimit ) // warning here
            doSomething();
    }
}

Could not get rid of the warning with Paul Omta answer, tried to write:

boost::optional<int> old;
if ( m_sizeLimit )
    old = boost::make_optional<int>(true, m_sizeLimit.value());
else
    old = boost::make_optional<int>(false, 0);

...with no success.

Did not want to completely disable the warning from my code, so I found an alternative solution I would recommend: disable the warning locally:

        #ifdef SDE_MOBILE
        #pragma GCC diagnostic push
        #pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
        #endif

        if ( old != m_sizeLimit ) // warning here
            doSomething();

        #ifdef SDE_MOBILE
        #pragma GCC diagnostic pop
        #endif