I've been playing with the following piece of code. file_string
returns a temporary string that should only "live" until the end of the statement. In Visual Studio 2008, when you use pTempFolder
, it contains rubbish as expected. In Linux though, with Intel compiler 11.0, pTempFolder
still points to a valid string. Do compilers have different policies regarding the destruction of temporaries, kind of eager (Visual) versus lazy (Intel)? Or maybe this is just a coincidence?
boost::filesystem wpathTempFolder("/tmp");
const wchar_t* const pTempFolder = wpathTempFolder.file_string().c_str();
// use pTempFolder
BTW, that is boost filesystem version 2. I've also seen that file_string
is being deprecated in boost filesystem version 3. And that there is a new c_str
method that operates over a string&, instead of over a temporary string.
/*filesystem 2*/
const string_type file_string() const;
/*filesystem 3*/
const string_type& native() const; // native format, encoding
const value_type* c_str() const; // native().c_str()
Likely, the string is still invalid, it just so happens that that section of memory hasn't yet been de-allocated at the operating system level and it "happens" to work. This program exhibits undefined behaviour- which always includes "may continue to work as if nothing went wrong". Visual Studio is completely correct here to crash your program or pretty much anything.