C++11 中 COW std::string 实现的合法性
据我所知,写时复制不是在 C++11 中实现符合标准的 std::string
的可行方法,但是当它最近在讨论中出现时,我发现我自己无法直接支持这种说法.
It had been my understanding that copy-on-write is not a viable way to implement a conforming std::string
in C++11, but when it came up in discussion recently I found myself unable to directly support that statement.
C++11 不承认基于 COW 的 std::string
实现,我是否正确?
Am I correct that C++11 does not admit COW based implementations of std::string
?
如果是,这个限制是否在新标准(where)的某处明确说明?
If so, is this restriction explicitly stated somewhere in the new standard (where)?
或者这个限制是隐含的,从某种意义上说,这是对 std::string
的新要求的综合影响,排除了基于 COW 的 std::string实现代码>.在这种情况下,我会对C++11 有效禁止基于 COW 的
std::string
实现"的章节和诗句风格派生感兴趣.
Or is this restriction implied, in the sense that it is the combined effect of the new requirements on std::string
that precludes a COW based implementation of std::string
. In this case, I'd be interested in a chapter and verse style derivation of 'C++11 effectively prohibits COW based std::string
implementations'.
推荐答案
这是不允许的,因为按照标准 21.4.1 p6,迭代器/引用失效只允许
It's not allowed, because as per the standard 21.4.1 p6, invalidation of iterators/references is only allowed for
――作为任何标准库函数的参数引用将非常量 basic_string 作为参数.
― as an argument to any standard library function taking a reference to non-const basic_string as an argument.
――调用非常量成员函数,除了 operator[]、at、front、back、begin、rbegin、结束,然后撕裂.
― Calling non-const member functions, except operator[], at, front, back, begin, rbegin, end, and rend.
对于 COW 字符串,调用非常量 operator[]
将需要进行复制(并使引用无效),这是上一段所不允许的.因此,在 C++11 中使用 COW 字符串不再合法.
For a COW string, calling non-const operator[]
would require making a copy (and invalidating references), which is disallowed by the paragraph above. Hence, it's no longer legal to have a COW string in C++11.
相关文章