CodexBloom - Programming Q&A Platform

std::string_view causing undefined behavior when used with std::thread in C++20

πŸ‘€ Views: 1 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-10
c++ std-string-view std-thread c++20 undefined-behavior C++

I'm not sure how to approach I'm dealing with Hey everyone, I'm running into an issue that's driving me crazy. I've been struggling with this for a few days now and could really use some help. I'm working with a serious scenario with `std::string_view` when using it in conjunction with `std::thread` in C++20. My intention is to pass a string view to a thread function, but it seems to lead to undefined behavior. Here’s a simplified version of my code: ```cpp #include <iostream> #include <string> #include <string_view> #include <thread> void threadFunction(std::string_view sv) { std::cout << sv << std::endl; } int main() { std::string str = "Hello, World!"; std::string_view sv = str; std::thread t(threadFunction, sv); t.join(); return 0; } ``` This code compiles and runs without errors, but I sometimes get garbage output or crashes, especially when accessing `sv` after the original string goes out of scope. I initially thought `std::string_view` would be a safe way to handle string references, but now I suspect the threading model might cause issues due to the string's lifetime. To troubleshoot, I tried changing `std::string_view` to `const std::string&`, and the crashes stopped, but I’m concerned about performance and copying overhead. I’ve also read that passing `std::string_view` by value should be fine, but is there something I’m missing in the context of threading? Any advice would be appreciated! I'm using g++ version 10.2.0 with C++20 enabled. Has anyone else encountered this? What is the best practice for passing strings to threads safely? I'm working on a CLI tool that needs to handle this. What am I doing wrong? Any advice would be much appreciated.