CodexBloom - Programming Q&A Platform

std::string_view causing dangling pointer issues in C++17 when used in a class

πŸ‘€ Views: 27 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-15
c++ string_view memory-management cpp

I'm working with an scenario with `std::string_view` in C++17 when it's being used as a member of a class. I have a class that stores a `std::string_view` pointing to a string that is passed during construction. However, when I try to access this string later, it seems to lead to dangling pointers after the original string goes out of scope. Here’s a simplified version of my code: ```cpp #include <iostream> #include <string> #include <string_view> class MyClass { public: MyClass(std::string_view str) : data(str) {} void print() const { std::cout << data << std::endl; } private: std::string_view data; }; int main() { { std::string test = "Hello, world!"; MyClass myObj(test); myObj.print(); // This works fine } // At this point, `test` is out of scope and destroyed. myObj.print(); // This leads to undefined behavior! } ``` When I compile this, I encounter no errors, but when I attempt to call `print()` outside the scope of `test`, it results in undefined behavior. I was under the impression that `std::string_view` was safe to use as long as the original string is alive. What am I missing here? Is there a best practice I should follow when using `std::string_view` in this context? Any suggestions on how to avoid this scenario without changing the design? Thanks in advance for your help!