0

I have these code and I found s will get invalid if it is a C-styled const string:

class has_a_str_ref {
  const string& str;

 public:
  has_a_str_ref(string const& s) : str(s) {}
  void show() { std::cout << str << std::endl; }
};
int main() {
  const char* s = "abc";
  // const char s[] = "abc"; // not work
  // string s = "abc"; // works
  has_a_str_ref x(s);
  std::cout << s << std::endl;
  x.show();
  std::cout << s << std::endl;
  return 0;
}

What happened behind it?

PS: compile with -fsanitize=address

Pluveto
  • 456
  • 5
  • 9
  • 3
    `has_a_str_ref` ctor will get a `const&` to a tmp `std::string` created from the char array. Keeping a reference to this tmp (in the `str` member) is not valid. – wohlstad Aug 03 '22 at 16:19
  • Ask yourself - when is your `std::string` created? When is it destroyed? A better question - should `has_a_str_ref` _ever_ accept a temporary string as its constructor parameter? – Drew Dormann Aug 03 '22 at 16:19
  • Side note: `-fsanitize=address` will apply at run-time. – πάντα ῥεῖ Aug 03 '22 at 16:31
  • Note: You can avoid accidents like these by adding a deleted constructor taking an rvalue reference to `std::string`: `has_a_str_ref(string&& s) = delete;`, but this won't 100% guarantee the you're safe: `auto strPtr = std::make_unique("abc"); has_a_str_ref x(*strPtr); strPtr.reset(); x.show();` – fabian Aug 03 '22 at 19:35

0 Answers0