CodexBloom - Programming Q&A Platform

C++14 std::string_view causing memory corruption when used with custom string class

👀 Views: 618 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-25
c++ string-view memory-management custom-classes C++

I'm a bit lost with I've looked through the documentation and I'm still confused about I've been struggling with this for a few days now and could really use some help. I tried several approaches but none seem to work. I'm working with a strange scenario while using `std::string_view` in combination with my custom string class. My custom string class is designed to manage memory more efficiently, but when I create a `std::string_view` from an instance of my class, it seems to lead to memory corruption issues down the line. Here's a simplified version of my code: ```cpp #include <iostream> #include <string> #include <string_view> class MyString { public: MyString(const char* str) : data(new char[strlen(str) + 1]) { strcpy(data, str); } ~MyString() { delete[] data; } const char* c_str() const { return data; } private: char* data; }; void func(std::string_view sv) { std::cout << sv << std::endl; } int main() { MyString myStr("Hello, World!"); std::string_view sv(myStr.c_str()); func(sv); return 0; } ``` The output looks fine initially, but when I try to use `myStr` after the function call, I get a segmentation fault. The scenario seems to arise from the lifetime of the string data. Since `std::string_view` does not own the data, I worry that I'm somehow mismanaging memory. I have also tried changing the ownership model, but it didn't help. I suspect that `std::string_view` is holding onto a pointer that becomes invalid when `myStr` goes out of scope, but I'm unsure how to properly handle this situation. Any insights on best practices for using `std::string_view` with custom string classes would be greatly appreciated! This is part of a larger application I'm building. Has anyone else encountered this? This is part of a larger API I'm building. What am I doing wrong? The project is a mobile app built with C++.