I know that in C++03, technically the std::basic_string
template is not required to have contiguous memory. However, I'm curious how many implementations exist for modern compilers that actually take advantage of this freedom. For example, if one wants to use basic_string
to receive the results of some C API (like the example below), it seems silly to allocate a vector just to turn it into a string immediately.
Example:
DWORD valueLength = 0;
DWORD type;
LONG errorCheck = RegQueryValueExW(
hWin32,
value.c_str(),
NULL,
&type,
NULL,
&valueLength);
if (errorCheck != ERROR_SUCCESS)
WindowsApiException::Throw(errorCheck);
else if (valueLength == 0)
return std::wstring();
std::wstring buffer;
do
{
buffer.resize(valueLength/sizeof(wchar_t));
errorCheck = RegQueryValueExW(
hWin32,
value.c_str(),
NULL,
&type,
&buffer[0],
&valueLength);
} while (errorCheck == ERROR_MORE_DATA);
if (errorCheck != ERROR_SUCCESS)
WindowsApiException::Throw(errorCheck);
return buffer;
I know code like this might slightly reduce portability because it implies that std::wstring
is contiguous -- but I'm wondering just how unportable that makes this code. Put another way, how may compilers actually take advantage of the freedom having noncontiguous memory allows?
EDIT: I updated this question to mention C++03. Readers should note that when targeting C++11, the standard now requires that basic_string
be contiguous, so the above question is a non issue when targeting that standard.
return std::wstring(vec.begin(), vec.end());
and get "create vector. Copy it to return value (via RVO)". I'd worry about whether I could detect the speed difference before I worried about how portable the resulting code was. But that's just this example, which is why it's a comment not an answer. – Sexpartitestd::wstring
for almost every win32 api call in my program. – Cohette