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

            Bug ID: 127470
           Summary: -Wmaybe-uninitialized false positive related to adding
                    const to pointer-to type, during class initialization
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
          Assignee: unassigned at gcc dot gnu.org
          Reporter: ivan.lazaric.gcc at gmail dot com
  Target Milestone: ---

Compiler flag, just "-Wmaybe-uninitialized"



```cpp
// Snippet 1:

const int* id(const int* p) { return p; }

struct S {
    const int* p;
    int x;
    S() : p(id(&x)), x(0) {}
};

S s;
```

This snippet emits warning:
```
<source>: In constructor 'S::S()':
<source>:6:15: warning: '<unknown>' may be used uninitialized
[-Wmaybe-uninitialized]
    6 |     S() : p(id(&x)), x(0) {}
      |             ~~^~~~
<source>:1:12: note: by argument 1 of type 'const int*' to 'const int* id(const
int*)' declared here
    1 | const int* id(const int* p) { return p; }
      |            ^~
```

If we change `id()` to take `int* p` instead, no warning is emitted.
If we change `id()` to both take and return `int*`, no warning is emitted.
If we omit `id()` in `p` initialization (so `p(&x)`), no warning is emitted.
If we change `id()` to take `const auto*`, YES warning is emitted.
If we change `id()` to take `auto*`, no warning is emitted.



```cpp
// Snippet 2: similar to 1, but the `id()` is now a constructor call

struct A { A(const int*) {} };

struct B {
    A a;
    int x;
    B() : a(&x), x(0) {}
};

B b;
```

This also emits the false positive warning.

Similar to snippet 1, if we change signature of `A::A()`,
`const auto*` warns, while `int*` and `auto*` doesn't.



In both snippets the order of members in {S,B} is important,
if we move `x` before {p,a}, warning is not emitted.

I've only tested on 86-64.

This behaviour is present in gcc versions: trunk, 16.2, 16.1.
This behaviour is not presend in gcc version 15.3.

If we consider optimization, no warning on `-O{1,2,3,s,z,g}`.
only saw warning on `-O0`.
Even if `id()` and `A::A()` are only declared, not defined,
the warning only shows up on `-O0`.

On godbolt: https://godbolt.org/z/1YdGM5zEa

Reply via email to