0

Given the following code

std::string_view foo(){
    std::string_view sv("ABC");
    return sv;
}

int main(){
   std::string_view svv = foo();
}
  1. Is it safe to say that since "ABC" is stored in the static area of the stack, svv is valid since the internal char array is still alive outside the scope of foo?
  2. Is it true that it will be called the constructor (4) at https://en.cppreference.com/w/cpp/string/basic_string_view/basic_string_view?
  3. If it were = "ABC", does 1. still hold?
  • Your general concern about the `std::string_view` referring to a function local string is valid, though in this special case string literals have lifetime that exist longer than the scope of the function they were defined – Cory Kramer Apr 21 '22 at 13:09
  • Nitpick: There's no such thing as "the static area of the stack"; there's the stack, and there is global data storage. To your questions: 1) It's safe (see duplicate). 2) Yep (using a literal form like `auto sv = "ABC"sv` would be slightly more efficient by using form (3) with a compile time constant known length, rather than requiring it to determine length at runtime). 3) Yep, it's still the same initialization whether you do `std::string_view sv("ABC");` or `std::string_view sv = "ABC";`. – ShadowRanger Apr 21 '22 at 13:11

0 Answers0