問題描述
據我所知,寫時復制不是在 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.
這篇關于C++11 中 COW std::string 實現的合法性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!