string.clear() does not remove element properly

It seems that member function clear() of string does remove its content, but the removed contents still can be accessed by operator[] . Here’s the example that makes me confused.

#include <iostream>
using namespace std;
int main()
    string input = "Weird";
    cout << "Your Input: " << input << "\n";
    cout << "Your Input: " << input << "\n";
    cout << "Your Input: " << input[0] << input[1] << input[2] << input[3] << input[4] << '\n';
    return 0;

The results are:

Your Input: Weird
Your Input:
Your Input: eird

Why this is happenning? If example above is normal, what should I do to completely remove its content? (accessing by input[1] should be ‘\000’)

>Solution :

Accessing elements of a string after calling the method clear invokes undefined behavior.

It seems in your case the class std::string uses its internal buffer defined within the class itself for short strings.

After the call of clear the class just set the first character of the buffer with the terminating zero character '\0;.

To check that string was cleared just output its length as for example

std::cout << input.length() << '\n';

Leave a Reply