The executable from the following code
#include <iostream>
#include <filesystem>
int main(void) {
std::string filename = "/home/amat/test.txt";
if (true) {
std::filesystem::path filename = std::filesystem::path(filename);
std::cout << "Filename (path): " << filename.string() << std::endl;
}
std::cout << "Filename (string): " << filename << std::endl;
return 0;
}
terminates with
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted
Why does this exactly happen? Not that one should seriously write code like this, but still, shouldn’t variable shadowing work here?
The std::filesystem::path constructor accepts a reference, yes, but why does it break?
>Solution :
In this line:
std::filesystem::path filename = std::filesystem::path(filename);
The filename used as an initializer is not the one you declared before the if, but rather the one that is just being declared in the current line.
But since its lifetime hasn’t started yet you invoke undefined behavior.
clang is giving a proper warning about it:
warning: variable 'filename' is uninitialized when used within its own initialization
Note that the filename you declared before the if is actually not relevant here.