Null terminator in the middle of a std::string

Is the output defined?
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string a = "Hello, Internet!";
    cout << a.size() << endl;
    a[5] = '\0';
    cout << a.size() << endl;
}
16
16
And furthermore, is it safe to do this?
Last edited on
> Is the output defined?

Yes, it is well defined.

> And furthermore, is it safe to do this?

Yes.

std::string holds a sequence of chars. The null character is just another char in the sequence.

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <string>

int main()
{
    std::string a( 80, 0 ) ; // creates a string having 80 chars, each char is a null char
    std::cout << a.size() << '\n' ; // prints: 80
    std::string b( 79, 0 ) ; // creates a string having 79 chars, each char is a null char
    std::cout << std::boolalpha << (a==b) << ' ' << (a>b) << '\n' ; // prints: false true
}

Cool, I wasn't sure if the standard maintained that implementations couldn't use null terminated implementations. Thanks!
Last edited on
What did you say?
I mean, I wasn't sure if the C++ language standard stated that std::string implementations can't just be wrappers for null-terminated character arrays.
Topic archived. No new replies allowed.