Home > Back-end >  Which std::string constructor am I using?
Which std::string constructor am I using?

Time:12-29

I see std::string has many constructors https://cplusplus.com/reference/string/string/string/.

But which one am I using when I do:

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

I bet is:

from c-string (4) string (const char* s);

(4) from c-string
Copies the null-terminated character sequence (C-string) pointed by s.

But isn't a c-string always null terminated? That s isn't according to my ide/debugger (Qt Creator on macOS).

Am I on undefined behavior territory?

Should I instead do the following?

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

CodePudding user response:

That s isn't according to my ide/debugger (Qt Creator on macOS).

Your debugger is likely just not showing the terminator. String literals are always null terminated. You can see it for yourself:

#include <iostream>

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

Output:

97
98
99
0

But if you create the string manually, you are responsible for the terminator:

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

CodePudding user response:

But isn't a c-string always null terminated?

Yes, string literals are null terminated. The debugger/ide might not be showing the null terminator in your case.

From string literal:

The type of an unprefixed string literal is const char[N], where N is the size of the string in code units of the execution narrow encoding (until C 23)ordinary literal encoding (since C 23), including the null terminator.


Am I on undefined behavior territory?

No, not at all. Both of the given snippets are well-formed.

CodePudding user response:

A string literal like "abc" is always null-terminated. You can use your first example. Typically you would write it like this though:

std::string str = "abc";

Edit, see comment below: Inside the string object str 'abc' it will most likely not be null-terminated (until you eventually call str.c_str()).

  • Related