Is it reasonable to use std::basic_string<t> as a contiguous buffer when targeting C++03?
c++, c++03, stl, string, winapi
Solution
I'd consider it quite safe to assume that std::string allocates its storage contiguously.
At the present time, all known implementations of `std::string` allocate space contiguously.
Moreover, the current draft of C++ 0x (N3000) [Edit: Warning, direct link to large PDF] requires that the space be allocated contiguously (§21.4.1/5):
The char-like objects in a basic_string object shall be stored contiguously. That is, for any basic_string object s, the identity &*(s.begin() + n) == &*s.begin() + n shall hold for all values of n such that 0 <= n < s.size().
As such, the chances of a current or future implementation of `std::string` using non-contiguous storage are essentially nil.
Problem
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.