public member function
<string>

std::basic_string::data

const charT* data() const;
const charT* data() const noexcept;
獲取字串資料
返回一個指向陣列的指標,該陣列包含與構成 basic_string 物件的值的字元相同的字元序列。

訪問地址data()+size()會產生未定義的行為:不能保證空字元會終止此函式返回的值所指向的字元序列。有關提供此類保證的函式,請參閱 basic_string::c_str

程式不得更改此序列中的任何字元。
返回一個指向包含以 null 結尾的字元序列(即 C 字串)的陣列的指標,該字元序列表示 basic_string 物件的當前值。

此陣列包括構成 basic_string 物件的值的相同字元序列,外加一個附加的終止 null 字元 (charT()) 在末尾。

返回的指標指向 basic_string 物件當前使用的內部陣列,以儲存符合其值的字元。

兩者都basic_string::databasic_string::c_str 是同義詞,並返回相同的值。

返回的指標可能會因進一步呼叫修改物件的其他成員函式而失效。

引數



返回值

指向 basic_string 物件的 C 字串表示形式的值的指標。

charTbasic_string 的字元型別(即,它的第一個模板引數)。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// string::data
#include <iostream>
#include <string>
#include <cstring>

int main ()
{
  int length;

  std::string str = "Test string";
  char* cstr = "Test string";

  if ( str.length() == std::strlen(cstr) )
  {
    std::cout << "str and cstr have the same length.\n";

    if ( memcmp (cstr, str.data(), str.length() ) == 0 )
      std::cout << "str and cstr have the same content.\n";
  }
  return 0;
}

輸出
str and cstr have the same length.
str and cstr have the same content.


複雜性、迭代器、訪問、異常

未指定或矛盾的規範。

複雜度

常量。

迭代器有效性

沒有變化。

資料競爭

該物件被訪問。

異常安全

無異常保證:此成員函式從不丟擲異常。

另見