mardi 2 février 2016

Check that string_view won't outlive its string object

I have a string_view class which is intended to be a drop-in replacement for std::string:

struct string_view {
  /* implicit */ string_view(const std::string& s) : ptr_(s.c_str()), size_(s.size()) {}
  // other ctors...

  const char* ptr_;
  size_t size_;
};

However while it's OK to write

void f(string_view sv);
f(std::to_string(123));

The string_view cannot outlive temporary string object, it would lead to UB (use-after-free)

string_view g(string_view sv) { return sv; }
string_view sv = g(std::to_string(123));
sv[0];

Another case of UB:

string_view sv = std::to_string(123);
sv[0];

Is there a way to catch such errors at compile time? (Other than a Clang plugin).

Aucun commentaire:

Enregistrer un commentaire