5 ms·
OK i'll bite. What's wrong with this? It functions as expected or am I missing something. Edit: NVM, for those wondering the std::string constructor copies the
by rhodysurf 6y ago
OK i'll bite. What's wrong with this? It functions as expected or am I missing something.
Edit: NVM, for those wondering the std::string constructor copies the string when it doesnt have to. But the solution here is to just initialize the string_view with the char data instead of the std::string instance
Edit: Ignore me see below
- steveklabnik 6y agoIsn't it a use-after free? (I haven't had time to compile and run it) You have a temporary std::string, pointed to by a string_view, which means that it's freed, and the view is dangling, and then used when printing things out.
- rhodysurf 6y agoSo thats what I initially thought but then I ran it and it works so IDK anything anymore.
- steveklabnik 6y agoUB can do anything, including something that seems like it works. Just because the memory has been deallocated doesn't mean that the bytes there were changed. The pointer may still point to them, and it may still "work."
- mlindner 6y agoIt's undefined behavior, so it'll literally print anything. On my system with my compiler version it'll print xyz without any optimization, but if I use -O3 optimization it prints nothing. But it could just as easily segfault or print garbage from memory. Edit: If I move the first line into a function and return that string_view, then with optimizations it still prints nothing, but without optimizations it prints random varying garbage each time I run it, different each time.
- clappski 6y agoThe issue isn’t anything to do with copying - the issue is that a string_view is a non-owning reference, and that std::string on the right side is an rvalue. Meaning that when you deref the char* in the string_view you’ll segfault or summon demons or something.
- rhodysurf 6y agoYeah I expected a segfault too... but it didnt happen for me and printed fine so I was confused.
- Jtsummers 6y agoTry putting it inside another function and then return the string_view before printing. The behavior will be more interesting. The first time I got "V", then consistently "f" or "+" after that. A lot of C++'s (and C's) memory "fun" doesn't readily appear when you're inside a particular function because the memory (like here) is on the stack. So your behavior within that function scope looks like what you want. Then you start returning values and, oops, something was a reference to memory on the stack. In which case it more or may not work depending on what else has happened between the value being placed on the stack and its use (I had to run a fun crash course for EEs on stack vs heap, when your only programming experience is a bit of Matlab this is not a topic you'll be familiar with).