Question

My application needs to manage a few of unicode strings (<10). The content of these strings is dynamic and can change through application run. To store strings I am using objects of type UnicodeString.

One approach to solving this problem is to create as many member variables as there are unicode strings like for example:

UnicodeString str1;

UnicodeString str2;

...

UnicodeString strN;

This solutions is pretty simple at least at first glance. But there is problem with scalability. If the number of string would rise in the future, we risk creating hard-to-read bigg code. So I thougth creating something like this for managing strings:

std::map<HWND, UnicodeString> file_names;    ///< member variable of form TForm1

Every string is connected with some edit box. I can use window handle as key to dictionary.

What I don't understand - who should be responsible for allocating and deallocating space for storing unicode string in this case? Lets say I create UnicodeString variable on local stack:

void TForm1::ProcessFile(TEdit *edit_box)
{
    UnicodeString str = "C:\\Temp\\ws.gdb";

    file_name[edit_box->Handle] = str;
}

Will the content of str variable survive end of member function ProcessFile?

Was it helpful?

Solution

The memory storage of a UnicodeString is reference counted and managed by the RTL for you. You do not need to worry about deallocating it yourself, unless you allocate the UnicodeString itself using the new operator. In your code snippet, the str variable will be freed when ProcessFile() exits, but its contents will survive because file_name still has an active reference to it.

Do not use an HWND as the key for your std::map. The window managed by the TWinControl::Handle property is dynamic and can change value during the lifetime of the app. You can, however, use the TEdit* pointer instead:

std::map<TEdit*, UnicodeString> file_names;

void TForm1::ProcessFile(TEdit *edit_box)
{
    UnicodeString str = "C:\\Temp\\ws.gdb";
    file_names[edit_box] = str;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top