uninitialized string

Jonathan Wakely jwakely.gcc@gmail.com
Mon Jan 21 17:39:00 GMT 2019

On Mon, 21 Jan 2019 at 17:29, Manfred <mx2927@gmail.com> wrote:
> On 1/21/2019 6:18 PM, Jonathan Wakely wrote:
> > On Mon, 21 Jan 2019 at 17:13, Manfred <mx2927@gmail.com> wrote:
> >>
> [...]
> >>
> >> I wonder why int triggers the warning, but std::string does not.
> >
> > Well for starters, std::string is not the same as int, not even close.
> I know, they obviously are very different objects, but that's not the point.

But it is the point. For std::string all GCC sees is a call to a
constructor that takes a reference, and that reference binds to a

Outside the constructor call, it's just a function call and a
reference that binds to an object. Inside the constructor, it's got a
reference which is assumed to be valid. Nothing tells the compiler
that the reference must bind to an initialized object, and the code
outside the constructor doesn't see the code inside, and vice versa.

For int, there's no function call to separate "inside the constructor"
and "outside the constructor" because there is no constructor. The
compiler knows exactly what "int n = n" does, and it clearly
initializes the variable with itself.

To make the two cases equivalent try:

int& f(int& i) { return i; }
int n = f(n);

This is closer to the std::string case, and now there's no warning.

Or even simpler:

int& n = n;

This also doesn't warn. That's

> >
> > It's pretty obvious when you think about it. Constructing a
> > std::string calls a constructor, in this case, it calls the
> > basic_string(const basic_string&) constructor, and passes the *this as
> > the argument, which makes a copy of the string. The problem is that
> > the string was never constructed, so it's a copy of garbage.
> That's it, the object is used before it is initialized.
> Apparently gcc is able to catch this with int (probably other types
> too), but not with string.

Because there's no constructor for int, but there's a constructor for

> >
> > Failing to warn about it is a longstanding and well-known defect in
> > GCC, you can find lots of discussion in bugzilla.
> >
> The following was reported:
> https://gcc.gnu.org/bugzilla/show_bug.cgi?id=71228
> Since this complains about int, but apparently int works today, I was
> wondering if anything is going on about string a well.

That's for C, not C++, and so isn't relevant here (the warning you get
for int comes from -Winit-self which is only for C++).

https://gcc.gnu.org/bugzilla/show_bug.cgi?id=52167 is exactly your case.

There are several related bugs like
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=48483 which apply to use
of uninitialized values inside constructors.

More information about the Gcc-help mailing list