I have an interface which is used like the following:
if (SUCCEEDED(pInterface->GetSize(&size))
{
wchar_t tmp = new wchar_t[size];
if (SUCCEEDED(pInterface->GetValue(tmp, size)))
{
std::wstring str = tmp;
// do some work which doesn't throw
}
delete[] tmp;
}
Is it safe and portable to do this instead?
if (SUCCEEDED(pInterface->GetSize(&size))
{
std::wstring str;
str.resize(size-1);
if (SUCCEEDED(pInterface->GetValue(&str[0], size)))
{
// do some work
}
}
Now, obviously this works (doesn’t crash/corrupt memory) or I wouldn’t have asked, but I’m mostly wanting to know if there’s a compelling reason not to do this.
Edit: Actually I had change this to .resize(size-1), as apparently the null character is taken into account for you (by VS 2010 anyway). Using .resize(size) ended up where appending to the end of the string was resulting in:
str.resize(size);
pInterface->GetValue(&str[0], size);
str contains L"foo\0";
str += L"bar";
str contains L"foo\0bar";
Trying to use the resulting str.c_str ends up looking like L”foo” due to the null in the middle.
As AraK points out, the string storage might not be contiguous, though this is unlikely. You could also consider using a vector:
which is more likely to be exception safe.