开发者

Compiler policies on destruction of temporaries

开发者 https://www.devze.com 2023-02-24 17:10 出处:网络
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, i

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 files开发者_JS百科ystem 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号