据我所知,写时复制不是std::string在C++ 11中实现符合性的可行方法,但最近在讨论中我发现自己无法直接支持该语句.
我是否正确C++ 11不承认基于COW的实现std::string?
如果是这样,这个限制是否在新标准(其中)的某处明确说明了?
或者这个限制是否暗示,因为新要求的综合影响std::string排除了基于COW的实施std::string.在这种情况下,我会对"C++ 11有效禁止基于COW的std::string实现" 的章节和样式推导感兴趣.
被std::string使用gcc 4时引用计数-std=c++0x或-std=c++11?
我知道在C++ 03中,从技术上讲,std::basic_string模板不需要具有连续的内存.但是,我很好奇有多少实现存在于实际利用这种自由的现代编译器.例如,如果想要用来basic_string接收某些C API的结果(如下面的例子),分配一个向量只是为了立即将它变成一个字符串似乎很愚蠢.
例:
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;
Run Code Online (Sandbox Code Playgroud)
我知道像这样的代码可能会略微降低可移植性,因为它意味着它std::wstring是连续的 - 但我想知道这个代码是多么不可移植.换句话说,编译器如何实际利用具有非连续内存的自由?
编辑:我更新了这个问题,提到C++ 03.读者应注意,在定位C++ 11时,标准现在要求basic_string是连续的,因此在定位该标准时,上述问题不是问题.
抱歉这么长的问题,但我尽量保持清醒.这在某种程度上遵循了我之前关于C++中的字符串的问题.我试图找出如何从没有冗余内存分配的函数返回std :: string,而不依赖于NRVO.我不想依赖NRVO的原因是:
请注意,我需要一个C++ 03兼容的解决方案(不幸的是没有C++ 0x rvalue引用......)
最简单的方法是传递引用并执行std :: swap,就像这样
void test(std::string& res)
{
std::string s;
//...
res.swap(s);
}
Run Code Online (Sandbox Code Playgroud)
但是按价值返回比通过引用传递更自然且更方便,所以我想要实现的是:
std::string test()
{
std::string s;
//...
return SOMETHING(s);
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,它只会swap使用"返回值",但我不知道如何在C++中执行此操作.有auto_ptr已经移动而不是复制,我实际上可以使用auto_ptr<string>,但我想避免动态分配字符串对象本身.
我的想法是以某种方式"标记"一个字符串对象,它从函数返回以允许在返回时调用复制构造函数时移动其数据.所以我最终得到了这个代码,它完全符合我的要求:
struct Str
{
struct Moveable
{
Str & ref;
explicit Moveable(Str & other): ref(other) {}
};
Str() {}
Str(const std::string& other) : data(other) {} // copy
Str(Moveable& other) { data.swap(other.ref.data); } // move
Moveable …Run Code Online (Sandbox Code Playgroud) 继续讨论这个问题后,我想知道如何使用本机C++以编程方式确定他们使用的std :: string实现是否利用了写时复制(COW)
我有以下功能:
#include <iostream>
#include <string>
bool stdstring_supports_cow()
{
//make sure the string is longer than the size of potential
//implementation of small-string.
std::string s1 = "012345678901234567890123456789"
"012345678901234567890123456789"
"012345678901234567890123456789"
"012345678901234567890123456789"
"012345678901234567890123456789";
std::string s2 = s1;
std::string s3 = s2;
bool result1 = (&s1[0]) == (&s2[0]);
bool result2 = (&s1[0]) == (&s3[0]);
s2[0] = 'X';
bool result3 = (&s1[0]) != (&s2[0]);
bool result4 = (&s1[0]) == (&s3[0]);
s3[0] = 'X';
bool result5 = (&s1[0]) != (&s3[0]); …Run Code Online (Sandbox Code Playgroud)