String Views

string_view vs const string&

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

Abstract art representing computer programming

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.

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