Following code is working and I am trying to understand how.
int Process::processTextFile(const boost::filesystem::path& infile)
{
const char *file = infile.string().c_str();
uint16_t num_lines = 0;
.
.
.
FILE *fp;
fp = fopen(file, "r");
.
.
//Use fp for reading and stuff.
}
From what I understand infile.string() creates a temporary and file points to the contents. Moment the statement ends (;) the temporary string should go out of scope leading to file being a dangling pointer.
I will be using string instead of char* but still need to understand what I am missing.
Compiler - gcc 4.8.4
Optimization - O3
C++ specifies that binding a temporary object to a reference to const on the stack lengthens the lifetime of the temporary to the lifetime of the reference itself, which means of const char *file which lies in the stack.
This C++ mechanism avoid what you pointed as dangling-reference error. In the code above, the temporary lives until the closing curly brace of your funtion processTextFile.
You can check this GOTW for more info.