2

Due to some accidental copy-paste, I ran into an interesting one liner that raises a lot of questions.

#include <string>

const std::string MY_STR{MY_STR + " hello"};

This compiles on gcc, clang, msvc both on x86 and ARM platforms, and after some digging it's just utilizing an uninitialized value for instantiation. But then I observed:

#include <string>

const std::string MY_STR{MY_STR.c_str()};

This I feel should fail to compile as I am trying to use MY_STR as an instance to retrieve the c_str() pointer.

What in the C++ standard, if anything, makes this legal?

mascoj
  • 1,313
  • 14
  • 27
  • `void *x = &x;` is legal, but your two examples are not. You are using `MY_STR` before it is initialized – 463035818_is_not_an_ai Apr 13 '23 at 21:29
  • @463035818_is_not_a_number The second example fails at runtime because `c_str` returns null, but I would except it to not compile. I am asking if the standard thinks it should. – mascoj Apr 13 '23 at 21:32
  • i might be wrong, but I am almost certain that it is undefined, ie compiler is not required to issue an error – 463035818_is_not_an_ai Apr 13 '23 at 21:34
  • related https://stackoverflow.com/questions/9820027/using-newly-declared-variable-in-initialization-int-x-x1 – 463035818_is_not_an_ai Apr 13 '23 at 21:37
  • this answer has the quote from the standard you are looking for https://stackoverflow.com/a/9820155/4117728 – 463035818_is_not_an_ai Apr 13 '23 at 21:37
  • `MY_STR` is uninitialized when you call `c_str()`. Once initialized `c_str` will never return a nullptr – 463035818_is_not_an_ai Apr 13 '23 at 21:42
  • Why is this legal? Smurfed if I know. Could be as simple as the effort required to conclusively prove that a mistake was made outweighs the perceived benefits of preventing the mistake with the compiler. – user4581301 Apr 13 '23 at 21:42
  • sometimes it is just what is needed. Eg the already mentioned `void* x = &x;` can make sense sometimes. Other times a constructor takes a pointer to same type and you want to be able to say `T foo(&foo);`. Unfortunately, when its a mistake it will still compile. – 463035818_is_not_an_ai Apr 13 '23 at 21:45

0 Answers0