CodexBloom - Programming Q&A Platform

std::string_view causing unexpected slicing when used with std::vector in C++17

πŸ‘€ Views: 120 πŸ’¬ Answers: 1 πŸ“… Created: 2025-07-11
c++17 stdstringview stdvector C++

I'm writing unit tests and I'm having an scenario with `std::string_view` and `std::vector` in C++17 that leads to unexpected string slicing... I have a vector of strings where I want to create views into the original strings without copying them. However, when I try to access a `std::string_view` after the original strings are modified, I'm getting unexpected behavior. Here's a simplified version of what I've done: ```cpp #include <iostream> #include <vector> #include <string> #include <string_view> int main() { std::vector<std::string> myStrings = {"Hello, world!", "Goodbye, world!"}; std::vector<std::string_view> views; for (const auto& str : myStrings) { views.push_back(str); } myStrings[0] = "Hello, C++17!"; for (const auto& view : views) { std::cout << view << '\n'; // Expecting "Hello, world!" and "Goodbye, world!" } } ``` After modifying `myStrings`, I expected the `views` to still point to the original strings, but instead, when I print the `views`, I see `Hello, C++17!` and `Goodbye, world!`. I thought `std::string_view` should not take ownership of the string, but rather just provide a view. What’s going wrong here? Am I missing something about the lifetime of `std::string_view` or the way I'm using the vector? I appreciate any insights! I'm working on a desktop app that needs to handle this. Could this be a known issue?