20

Possible Duplicate:
std::string length() and size() member functions

I always retrieved the length of an std::string via thesize() member function. To be honest I never knew there was a length() member function too. Well, I've just learnt there is. So I am wondering if there's any difference between the two, and in the likely event of a negative answer, why would there be two member functions that do exactly the same?

0

1 Answer 1

16

Nope! No difference. The more natural name for this function is length() and size() is provided alongside for uniformity with containers.

Sign up to request clarification or add additional context in comments.

10 Comments

@Armen: I don't have the book with me at the moment :)
This would be problematic if in the future the semantics change. Semantically speaking(aside STL semantics), size can reflect the number of bytes of the string) while the length can refer to the number of "characters" of that string. In ASCII the two give the same result, but this doesn't hold for other encodings like UTF etc.
I think it has more to do with the fact that size() is defined in every STL container, but length() sounds more familiar for strings, as explained in the accepted answer of the linked question. I don't think that ISO and ANSI ever had different versions of the standard. Even the (I think original) SGI STL documentation states that length is just a "Synonym for size()."
@sitifensys: length() is defined as returning size(); there's no way that could be changed at this point in time, too much code relies on that behavior.
@sitifensys: doesn't really matter, since std::basic_string has no notion of "characters" as being any different from its CharT template parameter, and CharT is what it is (very close to being) a container of. So size() and length() both fundamentally must mean the size measured in units of CharT. While size() might be the size in bytes in some languages, distinct from the length in characters, it won't ever be distinct for std::string, and isn't for std::wstring.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.