Working with String Views

std::string_view: Modifying Underlying String

What happens if the underlying string of a std::string_view is modified?

Abstract art representing computer programming

std::string_view provides a non-owning view of a string, allowing efficient access without copying.

However, modifying the underlying string while a std::string_view points to it can lead to undefined behavior or unexpected results.

Direct Modifications

When the underlying string is modified directly, std::string_view reflects those changes, but the results might be unpredictable:

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

int main() {
  std::string str{"Hello, World!"};
  std::string_view view{str};

  std::cout << "Original view: " << view << "\n";

  // Modify the underlying string
  str[7] = 'C';
  std::cout << "Modified view: " << view << "\n";
}
Original view: Hello, World!
Modified view: Hello, Corld!

In this example, view reflects the modification of str. This can be useful, but it's crucial to ensure the modifications are intentional and understood.

Resizing the Underlying String

If the underlying string is resized, especially shrunk, std::string_view can become invalid, leading to undefined behavior:

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

int main() {
  std::string str{"Hello, World!"};
  std::string_view view{str};

  std::cout << "Original view: " << view << "\n";

  // Resize the underlying string
  str.resize(5);
  std::cout << "Resized view: " << view;  
}
Resized view: Hello
undefined behavior or corrupted output

Here, resizing str may leave view pointing to invalid memory, causing undefined behavior.

Reallocations

When the underlying string undergoes reallocation (e.g., during a push_back operation), std::string_view might point to an old, deallocated memory area:

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

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

  std::cout << "Original view: " << view << "\n";

  // Trigger reallocation
  str += ", World!";
  std::cout << "Reallocated view: " << view;  
}
Original view: Hello
Reallocated view: Hello or undefined behavior

The reallocation invalidates the view, potentially leading to undefined behavior.

Conclusion

While std::string_view is efficient, care must be taken when modifying the underlying string. Ensure modifications are safe and the lifetime of the string outlasts the std::string_view to avoid undefined behavior.

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

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