简体   繁体   English

关于临时人员销毁的编译器政策

[英]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. file_string返回一个临时字符串,该字符串只应“有效”直到语句结束。 In Visual Studio 2008, when you use pTempFolder , it contains rubbish as expected. 在Visual Studio 2008中,当您使用pTempFolder ,它包含预期的垃圾。 In Linux though, with Intel compiler 11.0, pTempFolder still points to a valid string. 但是,在Linux中,使用Intel编译器11.0, pTempFolder仍指向有效的字符串。 Do compilers have different policies regarding the destruction of temporaries, kind of eager (Visual) versus lazy (Intel)? 编译器在临时性销毁方面是否有不同的政策,即渴望(Visual)与懒惰(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. 顺便说一句,这是boost文件系统版本2。我还看到在boost文件系统版本3中不推荐使用file_string ,并且有一个新的c_str方法对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. Visual Studio在这里完全正确,可以使您的程序或几乎任何东西崩溃。

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). 返回值std::string::c_str()指向的数组对象的生存期不超过字符串对象本身的生存期(如果在字符串上调用任何非const函数,则生存期可能会缩短)。 Accessing an object after its lifetime has ended is undefined behavior, so you cannot draw any conclusions from what the compiler does. 在对象的生存期结束后访问对象是未定义的行为,因此您不能从编译器的操作中得出任何结论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM