Search code examples
stdstring

Why do basic_string::size() & '_M_string_length' in same class, return **different** values, even though size() returns 'size_type _M_string_length'?


I wanted to see the actual definition of this function size() and lenght() of basic_string, because in his book, Bjarne had written that 'strlen() is a log(N) opera- tion, whereas string::size() is a simple read'. And then I found that, there is '_M_string_length' (declared private at line 156 in bits/basic_string.h)

I made the _M_string_length member public in the class (and commented the private one).

But,

std::string str="Hello"
std::cout<<str._M_string_length<<'\n'<<str.length()<<'\n'<<str.size()<<'\n';

gave this output:

140723012417600       //kept changing in various runs
5
5

Why is _M_string_length and size() are different... even though size() also returns _M_string_length as it is, and it's type is also size_type? Is it due to that _GLIBCXX_NOEXCEPT?

For the _GLIBCXX_NOEXCEPT, i ran the following...

cat /usr/include/c++/7.4.0/bits/* | grep "#define _GLIBCXX_NOEXCEPT"

and in all directories inside them... like /usr/include/ and /c++/7/ and its subdirectories but i couldn't find if it.


Solution

  • You can't safely edit/change anything in the std namespace and expect to have it work in a sensible way. You get undefined behavior.

    What probably happened is that your change changed the layout of the basic_string class, but you're still linking with the same libstdc++ shared library object that is assuming the old layout, so things break randomly.