On Mon, 21 Jan 2019 at 17:13, Manfred <mx2927@xxxxxxxxx> wrote: > > The following was asked on comp.lang.c++; > It compiles and crashes with no error/warning on gcc 8.2.1: > > #include <iostream> > #include <string> > > int main() > { > std::string s1 { s1 }; > std::string s2(s2); > std::string s3 = s3; > > std::cout << s1 << s2 << s3; > } > > [tmp]$ g++ -Wall selfref.cc && ./a.out > Segmentation fault (core dumped) > [tmp]$ > > On the other hand: > > #include <iostream> > > int main() > { > int n { n }; > > std::cout << n << std::endl; > } > > [tmp]$ g++ -Wall selfint.cc && ./a.out > selfint.cc: In function ‘int main()’: > selfint.cc:5:7: warning: ‘n’ is used uninitialized in this function > [-Wuninitialized] > int n { n }; > ^ > 0 > [tmp]$ > > 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. 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. Failing to warn about it is a longstanding and well-known defect in GCC, you can find lots of discussion in bugzilla.