gbro3n
gbro3n

Reputation: 6967

Why is the data in variable different when using these two sets of statements?

When I attempt to get the c_str by accessing the result of the type conversion function, parantheses included, the string is empty.

const wchar_t* test1 = (type_conversion.string_to_wstring(result1)).c_str();

// test1 contains empty string "";

When I use an intermediate variable 'testWstring', the result is different - I have the contents that were originally in 'result1' as I would expect.

wstring testWstring = type_conversion.string_to_wstring(result1);

const wchar_t* test1 = testWstring.c_str();

// test1 contains "hi";

The typeConversion.string_to_wstring function looks like this:

wstring type_conversion::string_to_wstring(const string& str)
{
    int len;
    int slength = (int) str.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, 0, 0); 
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

I've obviously misunderstood something here. Coming from a C# background, I would expect the two sets of statements to result in the same value in 'test1'.

Why is this not the case?

Upvotes: 0

Views: 62

Answers (2)

David
David

Reputation: 9945

The result of calling string_to_wstring is not bound to a reference or assigned to object. It is destructed at the end of the full-expression. See also sequence-point.

In the second example you assign the result to a variable which is retained in the scope.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310920

The result of executing function string_to_wstring is a temporary object. In this statement

const wchar_t* test1 = (typeConversion.string_to_wstring(result1)).c_str();

it will be deleted when the control will be passed further. So the code has undefined behaviour.

In the second case you are using pointer to internal buffer of an alive object. So until the objevt will be changed the pointer will be valid.

Upvotes: 1

Related Questions