Referring to the contents of c++ temporary strings

600 Views Asked by At

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

2

There are 2 best solutions below

4
Conjecture On

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.

0
Rabbid76 On

infile.string() returns an object of type std::string. And .c_str() returns a pointer to some content of the object, so file is a pointer to the content of the object. But at the end of the statement the std::string object and its content gets destructed. As result, the pointer file points to nowhere, at the begin of the next statement.