编译器关于销毁临时文件的策略
我一直在玩下面的代码。 file_string
返回一个临时字符串,该字符串只能“存活”到语句结束。在 Visual Studio 2008 中,当您使用 pTempFolder
时,它会按预期包含垃圾。但在 Linux 中,使用 Intel 编译器 11.0,pTempFolder
仍然指向有效的字符串。编译器对于临时对象的销毁是否有不同的策略,即急切的(Visual)与惰性的(Intel)?或许这只是一个巧合?
boost::filesystem wpathTempFolder("/tmp");
const wchar_t* const pTempFolder = wpathTempFolder.file_string().c_str();
// use pTempFolder
顺便说一句,这是 boost 文件系统版本 2。我还看到 file_string
在 boost 文件系统版本 3 中已被弃用。并且有一个新的 c_str
方法可以在字符串&,而不是临时字符串。
/*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()
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()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
很可能,该字符串仍然无效,只是碰巧该内存部分尚未在操作系统级别取消分配,并且它“碰巧”可以工作。该程序表现出未定义的行为,其中始终包括“可能会继续工作,就好像没有发生任何问题一样”。 Visual Studio 在这里完全正确地使您的程序或几乎任何东西崩溃。
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.
临时对象的生命周期(有少数例外)直到
完整表达式结束。指向的数组对象的生命周期
通过
std::string::c_str()
的返回值不超过字符串对象本身的长度(并且可能更短,如果有的话)
在字符串上调用非常量函数)。访问
对象在其生命周期结束后是未定义的行为,所以
您无法从编译器的行为中得出任何结论。
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 excedethat 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.