rturrado
rturrado

Reputation: 8074

Compiler policies on destruction of temporaries

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()

Upvotes: 2

Views: 189

Answers (2)

James Kanze
James Kanze

Reputation: 154017

The lifetime of a temporary (with a few exceptions) is until the end of the full expression. The lifetime of the array object pointed to by the return value of std::string::c_str() does not excede that of the string object itself (and may be shorter, if any non-const functions are called on the string). Accessing an object after its lifetime has ended is undefined behavior, so you cannot draw any conclusions from what the compiler does.

Upvotes: 2

Puppy
Puppy

Reputation: 146998

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.

Upvotes: 6

Related Questions