Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this how the size() function really works in std::string?

Tags:

c++

I wrote a simple function that can get the size of a std::string class object, and I know that size() function in std::string does the same job, So I wanted to know if the size() function really works like my function or if it is more complicated? If it's more complicated, then how?

int sizeOfString(const string str) {
    int i=0;
    while (str[i] != '\0') {
        ++i;
    }
    return i;
}
like image 803
Farbod Ahmadian Avatar asked Sep 10 '26 02:09

Farbod Ahmadian


1 Answers

An std::string can contain null bytes, so your sizeOfString() function will produce a different result on the following input:

std::string evil("abc\0def", 7);

As for your other question: the size() method simply reads out an internal size field, so it is always constant time, while yours is linear in the size of the string.

You can peek at the implementation of std::string::size for various implementations for yourself: libc++, MSVC, libstdc++.

like image 183
Botje Avatar answered Sep 12 '26 16:09

Botje



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!