假设我们有一个来自其他地方的字符串,后来用作接受宽字符串的函数的输入参数。
在Variant 1中,Unicode字符串是从char字符串创建的,第二步是用作指向LoadLibrary()函数的wchar_t *指针。
将其缩短为一个代码行是否总是安全的,如变体2中所述?特别是,临时UnicodeString对象在函数本身使用期间是否总是足够长?是否有任何特殊情况会导致早期破坏物体?
char *libstr = "test.dll";
//...
//Variant 1
UnicodeString us(libstr);
HINSTANCE lib = LoadLibrary( us.w_str() );
//Variant 2
HINSTANCE lib = LoadLibrary( UnicodeString(libstr).w_str() );
谢谢,
编辑: @David Heffernan 感谢您指出有关C ++中临时参数的生命周期的回答问题 由于这是Delphi和C ++ Builder中UnicodeString和AnsiString对象的特定问题,并且使用Pascal在VCL中对这些对象进行编码,我仍然对这个主题感到疑惑,我觉得你的链接并没有涵盖100%的主题,尽管它对这个主题非常有帮助。谢谢。
答案 0 :(得分:2)
I originally closed this as a duplicate of this question: C++: Life span of temporary arguments?
I believe that closure is valid. The answers there tell you that:
Temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created.
Which means that your temporary outlives the function call and is safe.
You objected to the closure as duplicate by arguing that the classes in question were not C++ classes. But that is a mistaken belief. They are C++ classes. And the C++ rules apply.