C & C++

C & C++

Made by DeepSource

Dangling references in value handles std::string_view CXX-W2004

Bug risk
Minor

The std::string_view handle outlives it's data source instance.

std::string_view is a lightweight handle that provides transparent read access to a string. The key benefit is allowing access to the substring without incurring the overhead of creating a copy or temporary std::string. Being a handle to data also means that the std::string_view handle may outlive its data source, becoming a dangling handle.

Consider a scenario where you create a std::string_view handle for a temporary std::string instance. If the temporary instance is destroyed after the handle is created but is still in use, then the handle becomes a dangling reference and accessing it results in undefined behavior.

In general, it is best to avoid creating std::string_view handles for temporary std::string instances. It's always better to create a std::string_view from a std::string instance with a longer lifespan or use std::string_view for the data only if you can assure its lifetime.

Bad practice

// Bad example 1
string_view SRef = string();

string OtherString;
// Bad example 2
View = OtherString + "s";

vector<string_view> V;
// Bad example 3
V.push_back(string());

// Bad example 4
V.resize(3, string());

string_view f() {
  // Bad example 5: Following return value will dangle
  return string();

  string S;
  return S;

  char Array[10]{};
  return Array;
}

Recommended

string S = string();
string_view SRef = S;

string MoreString = S + "s";
string_view View = MoreString;

vector<string_view> V;
string S = string();
V.push_back(S);

V.resize(3, S);

string f() {
  /// Returning a reference to string should be avoided, as NRVO will take care of optimising the memory allocation
  return string();

  string S;
  return S;

  char Array[10]{};
  return Array;
}