String Views

Handle dangling string_view

How do I safely handle dangling std::string_view?

Abstract art representing computer programming

Handling dangling std::string_view safely is crucial because using a std::string_view that references deallocated memory leads to undefined behavior. Here are some best practices to avoid dangling std::string_view:

Ensure String Lifespan

Make sure the original string outlives the std::string_view. Avoid returning std::string_view from functions that create local strings:

#include <string_view>

std::string_view getStringView() {
  std::string temp{"Hello"};      
  return std::string_view{temp};  
}

int main() {
  std::string_view view = getStringView();
}

The above code is problematic because temp is destroyed when the function exits, leaving view dangling. Instead, return the std::string itself:

#include <string>
#include <string_view>

std::string getString() {
  return std::string{"Hello"};
}

int main() {
  std::string str = getString();
  std::string_view view{str};  
}

Use String Literals

For static strings, use string literals, which have static storage duration:

#include <string_view>

int main() {
  std::string_view view{"Hello, world"}; 
}

Avoid Temporary Strings

When initializing a std::string_view, ensure it doesn't refer to a temporary string:

#include <string>
#include <string_view>

int main() {
  using namespace std::string_literals;
  std::string_view view{"Hello"s}; 
}

Instead, use string literals or persistent strings:

#include <string_view>

int main() {
  std::string_view view{"Hello"}; 
}

By following these practices, you can avoid common pitfalls and ensure your std::string_view remains valid throughout its usage.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved