首頁  >  文章  >  後端開發  >  C 11 的 `string::c_str()` 仍然保證以 Null 結尾的字串嗎?

C 11 的 `string::c_str()` 仍然保證以 Null 結尾的字串嗎?

Mary-Kate Olsen
Mary-Kate Olsen原創
2024-10-27 15:35:02344瀏覽

 Does C  11's `string::c_str()` Still Guarantee a Null-Terminated String?

C 11 的 string::c_str() 函數不再以 Null 結尾嗎?

在 C 中, basic_string 類別提供了各種方法存取其字元。其中一個方法 c_str() 自 C 11 以來一直是混亂的根源。在 C 11 之前,c_str() 負責傳回表示字串內容的以 null 結尾的字元陣列。

但是,在 C 11 中,basic_string::c_str() 的定義已更改。現在它被定義為與 basic_string::data 相同,後者返回一個指向字串內部字元緩衝區開頭的指標。這提出了一個問題:此更改是否意味著 c_str() 不再保證以 null 結尾的字串?

答案:字串內部需要以 null 結尾的緩衝區

這個問題的答案是否定的。儘管 C 11 中發生了變化,字串仍然需要在內部使用空終止緩衝區。這從C 標準中的operator[]方法(21.4.5)的定義中可以明顯看出:

Requires: pos <= size().
Returns: *(begin()+pos) if pos < size(), otherwise a reference to an object of type T with value charT(); the referenced value shall not be modified.

c_str() 是根據operator[]定義的:

Returns: A pointer p such that p + i == &operator[](i) for each i in [0,size()].

由於c_str() 和data 都需要O(1) 運算,因此實際上強制實作使用以null 結尾的緩衝區。此外,operator[] 的回傳值要求可確保 c_str() 傳回指向以 null 結尾的緩衝區的指標。因此,儘管 C 11 中發生了變化,c_str() 仍然提供以 null 結尾的字串。

以上是C 11 的 `string::c_str()` 仍然保證以 Null 結尾的字串嗎?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn