簡體   English   中英

我使用的是哪個 std::string 構造函數?

[英]Which std::string constructor am I using?

我看到 std::string 有很多構造函數https://cplusplus.com/reference/string/string/string/

但是當我這樣做時我使用的是哪一個:

const char* s = "abc";
string str(s);

我打賭是:

來自 c-string (4) string (const char* s);

(4) 來自 c 字符串
復制 s 指向的空終止字符序列(C 字符串)。

但是 C 字符串不是總是以 null 終止嗎? 那不是根據我s ide/調試器(macOS 上的 Qt Creator)。

我在未定義的行為領域嗎?

我應該改為執行以下操作嗎?

const char* s = "abc";
string str(s, 3);

那不是根據我s ide/調試器(macOS 上的 Qt Creator)。

您的調試器可能只是沒有顯示終止符。 字符串文字始終以 null 結尾。 你可以自己看看:

#include <iostream>

int main() {
    for (char ch : "abc") {
        std::cout << +ch << '\n';
    }
}

Output:

97
98
99
0

但是,如果您手動創建字符串,則您要對終止符負責:

char cs1[] {'a', 'b', 'c'};        // not null terminated
char cs2[] {'a', 'b', 'c', '\0' }; // properly terminated
std::string s1(cs1);               // undefined behavior
std::string s2(cs2);               // OK

但是 C 字符串不是總是以 null 終止嗎?

是的,字符串文字以 null 結尾。 在您的情況下,調試器/ide 可能不會顯示 null 終止符。

字符串文字

無前綴字符串文字的類型是const char[N] ,其中N是字符串的大小,以執行窄編碼(C++23 前)普通文字編碼(C++23 起)的代碼單元表示,包括null 終止符


我在未定義的行為領域嗎?

一點都不。 給定的兩個片段都是格式正確的。

像“abc”這樣的字符串文字總是以 null 結尾。 你可以使用你的第一個例子。 通常你會這樣寫:

std::string str = "abc";

編輯,參見下面的評論:在字符串 object str 'abc' 中,它很可能不會以 null 結尾(直到您最終調用 str.c_str())。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM