https://gcc.gnu.org/bugzilla/show_bug.cgi?id=114253
Bug ID: 114253
Summary: False positive maybe-uninitialized with std::optional
and ternary
Product: gcc
Version: 8.3.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: tree-optimization
Assignee: unassigned at gcc dot gnu.org
Reporter: overdijk at gmail dot com
Target Milestone: ---
The following warning is reported:
> mwe.cpp: In function ‘int main()’:
> mwe.cpp:26:13: warning: ‘pid’ may be used uninitialized in this function
> [-Wmaybe-uninitialized]
> kill_pid(*pid);
> ^~
When compiling this minimum working example:
#include
#include
std::optional get_pid()
{
return std::nullopt;
}
void kill_pid(int)
{
}
int main()
{
std::string s;
volatile bool is_running = true;
std::optional pid = is_running ? get_pid() : std::nullopt;
kill_pid(0);
if (pid)
kill_pid(*pid); // no warning
if (pid)
kill_pid(*pid); // warning: 'pid' may be used uninitialized in this
function [-Wmaybe-uninitialized]
}
With the following compiler command line:
$ g++ -std=c++17 -O1 -fPIC -Wmaybe-uninitialized mwe.cpp
I think it is a false positive, since *pid is only used after verifying that it
is valid.
If any of these changes are made, the warning is no longer reported:
* Replace std::optional by a plain int*
* Remove the std::string variable (or replace it by something simple such as
int)
* Remove the first or second call to kill_pid
* Changing the ternary (e.g. `is_running ? std::optional{999} :
std::nullopt`)
* Removing -O1 or -fPIC from the command line (a higher optimization level is
fine)
I observed it with gcc 8.3.0, but it can be reproduced with gcc 8.1 through
13.2 as can be seen on godbolt:
https://godbolt.org/z/TYqYdfc77