string_view vs const string&

When should I use std::string_view instead of const std::string&?

std::string_view and const std::string& are both used for read-only access to strings, but they have different use cases and benefits.

Use std::string_view when:

  • You need to provide a unified interface for different string types (e.g., std::string, C-style strings, and string literals).
  • Performance is critical, and you want to avoid unnecessary copying.
  • You are working with substrings or portions of strings without copying.

Use const std::string& when:

  • You are certain that your function will only accept std::string objects.
  • The lifetime of the string is tightly controlled, and there is no risk of dangling references.

Here's an example comparing the two:

#include <iostream>
#include <string>
#include <string_view>

void printStringView(std::string_view sv) {
  std::cout << sv << '\n';
}

void printConstStringRef(const std::string& str) {
  std::cout << str << '\n';
}

int main() {
  std::string str{"Hello, world"};

  // Works with std::string
  printStringView(str);

    // Works with C-style string
  printStringView("Hello, C-style string");

  // Works with std::string
  printConstStringRef(str);

  // Error: incompatible types
  // printConstStringRef("Hello, C-style string"); 
}
Hello, world
Hello, C-style string
Hello, world

In summary, std::string_view offers greater flexibility and efficiency when handling various string types and avoiding unnecessary copying.

However, const std::string& is straightforward and ideal for cases where you are sure only std::string objects will be used.

String Views

A practical introduction to string views, and why they should be the main way we pass strings to functions

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Convert string_view to string
How do I convert a std::string_view back to a std::string?
Modify string through string_view
Can I modify the contents of a string through a std::string_view?
wstring_view vs string_view
How does std::wstring_view differ from std::string_view?
Handle dangling string_view
How do I safely handle dangling std::string_view?
string_view performance benefits
How does std::string_view improve performance compared to std::string?
Concatenate string_views
Is it possible to concatenate two std::string_view objects?
string_view vs span
What is the difference between std::string_view and std::span?
string_view in multithreading
Can I use std::string_view in multithreaded applications?
string_view to C-style string
How do I convert a std::string_view to a C-style string safely?
string_view and Encoding
How does std::string_view interact with different character encodings?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant