这是临时 std::string 的正确使用吗?
std::string getMyString() { return <make a string>; }
...
HANDLE something = OpenSomething(getMyString().c_str(), ...);
我读过 C++ 中临时变量的保证生命周期,我相信临时变量字符串将一直存在,直到分配被评估为止,即足够长的时间以使这项工作按预期进行。
之前曾经遇到过与生命周期相关的 std::string
错误(不记得那是什么),我宁愿仔细检查......
std::string getMyString() { return <make a string>; }
...
HANDLE something = OpenSomething(getMyString().c_str(), ...);
I've read Guaranteed lifetime of temporary in C++ and I believe that the temporary string will live until the assignment has been evaluated, i.e. plenty long enough to make this work as expected.
Having once before run into an std::string
lifetime-related bug (can't remember what it was) I'd rather double-check...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,这很好。 :-)
该字符串将在语句末尾的分号处被销毁。
Yes, this is fine. :-)
The string will be destroyed at the end of the statement, at the semi colon.
直到函数调用返回后才会调用临时的析构函数,因此我们在这里看到的是安全的。
但是如果被调用的函数保存了
char*
并且它最终在OpenSomething
返回后以某种方式被使用,那么那是一个很好的悬空指针。The destructor for the temporary will not be called until after the function call returns, so what we see here is safe.
However if the called function saves the
char*
and it ends up being used somehow afterOpenSomething
has returned, then that's one fine dangling pointer.如果您不使用
OpenSomthing
的任何其他参数来返回指向getMyString.c_str()
的指针,一切都会正常。If you don't use any other argument of
OpenSomthing
for returning pointer togetMyString.c_str()
everything will be OK.