Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have code similar to the following:

#include <boost/optional.hpp>

::boost::optional<int> getitem();

int go(int nr)
{
  boost::optional<int> a = getitem();
  boost::optional<int> b;

  if (nr > 0)
    b = nr;

  if (a != b)
    return 1;

  return 0;
}

When compiling with GCC 4.7.2 with Boost 1.53, using the following command:

g++ -c -O2 -Wall -DNDEBUG

The following warning is issued:

13:3: warning: ‘((void)& b +4)’ may be used uninitialized in this function [-Wmaybe-uninitialized]

Apparently, the root problem lies with GCC. See GCC Bugzilla Does anyone know a workaround?

like image 646
Paul Omta Avatar asked Feb 13 '14 13:02

Paul Omta


2 Answers

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.

like image 92
Matthieu M. Avatar answered Oct 04 '22 23:10

Matthieu M.


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...

like image 45
Paul Omta Avatar answered Oct 04 '22 22:10

Paul Omta