問題描述
我知道在 C++03 中,從技術上講,std::basic_string
模板不需要具有連續內存.但是,我很好奇有多少現代編譯器真正利用了這種自由的實現.例如,如果想使用 basic_string
來接收某些 C API 的結果(如下例所示),分配一個向量只是為了立即將其轉換為字符串似乎很愚蠢.
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.
示例:
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;
我知道這樣的代碼可能會稍微降低可移植性,因為它意味著 std::wstring
是連續的——但我想知道這段代碼是多么不可移植.換句話說,編譯器如何真正利用非連續內存所允許的自由?
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?
我更新了這個問題以提及 C++03.讀者應該注意,當以 C++11 為目標時,標準現在要求 basic_string
是連續的,因此當以該標準為目標時,上述問題不是問題.
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.
推薦答案
我認為假設 std::string 連續分配其存儲空間是非常安全的.
I'd consider it quite safe to assume that std::string allocates its storage contiguously.
目前,std::string
的所有已知實現都是連續分配空間的.
At the present time, all known implementations of std::string
allocate space contiguously.
此外,C++ 0x (N3000) 要求連續分配空間(第 21.4.1/5 節):
Moreover, the current draft of C++ 0x (N3000) requires that the space be allocated contiguously (§21.4.1/5):
在一個類似字符的對象應存儲 basic_string 對象連續.也就是說,對于任意basic_string 對象 s,身份&*(s.begin() + n) == &*s.begin() + n應適用于 n 的所有值,這樣0 <= n
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().
因此,std::string
當前或未來實現使用非連續存儲的可能性基本上為零.
As such, the chances of a current or future implementation of std::string
using non-contiguous storage are essentially nil.
這篇關于使用 std::basic_string<t> 是否合理?作為目標 C++03 時的連續緩沖區?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!