According to an article (here and there) this code is an erroneous use-after free example:
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string s = "Hellooooooooooooooo ";
std::string_view sv = s + "World\n";
std::cout << sv;
}
In the article it is stated that the string
s will be freed when the string_view
is used! This goes against my debugging experience. But I'm asking you to confirm/verify/check this.
In my experience, stack/scope variables are freed (calling the destructor would be a far more correct wording) at the exit of the scope. This means that in this case, this would happen AFTER the std::cout << sv;
However I have never used string_view
, so I don't know about any internal mechanics of this object.
If indeed it is a dangerous behaviour, could you explain it? Otherwise, I'd be glad to read the confirmation that scope variables destructors are called only at the exit of the current scope, naturally, or when an exception is thrown, interrupting the thread in the current scope.
EDIT: After the first two answers, it is really a use-after-free usage.
Subsidiary question: Do you think we could add a move constructor with the delete keyword in the definition of string_view so as to forbid that?