Search code examples
delphic++buildervcl

Is it always safe to give a temporary AnsiString or UnicodeString object as parameter to a function?


Let's assume we have a char string from somewhere else, which is later on used as an input parameter on a function which accepts wide strings.

In Variant 1, a UnicodeString is created from the char string and in a second step used as a wchar_t* pointer to the LoadLibrary() function.

Is it always safe to shorten this into one code line as written in Variant 2? In particular, will the temporary UnicodeString object always live long enough during its usage in the function itself? Could there be any special circumstances which would destroy the object to early?

char *libstr = "test.dll";
//...

//Variant 1
UnicodeString us(libstr);
HINSTANCE lib = LoadLibrary( us.w_str() );

//Variant 2
HINSTANCE lib = LoadLibrary( UnicodeString(libstr).w_str() );

Thanks,

Edit: @David Heffernan Thanks for pointing to the answered question regarding Life span of temporary arguments in C++ As this is a specific question for UnicodeString and AnsiString objects in Delphi and C++ Builder, and there these objects are coded in the VCL using Pascal, I am still wondering about the topic and I feel your link does not cover the topic 100%, although it is very helpful on the subject. Thank you.


Solution

  • 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.