Why sizeof() of a string variable always return the same number even when content changes?

人走茶凉 提交于 2019-12-02 17:01:12

问题


This is a rather simple problem but is pretty confusing.

string R = "hhhh" ;
cout<< sizeof( R )<<endl;

OUTPUT:

4

Variation:

string R = "hhuuuuuuhh" ; cout<< sizeof( R )<

OUTPUT2:

4

What is going wrong ? Should I use char array instead ?


回答1:


Think of sizeof being compile-time evaluable. It evaluates to the size of the type, not the size of the contents. You can even write sizeof(std::string) which will be exactly the same as sizeof(foo) for any std::string instance foo.

To compute the number of characters in a std::string, use size().

If you have a character array, say char c[6] then the type of c is an array of 6 chars. So sizeof(c) (known at compile-time) will be 6 as the C++ standard defines the size of a single char to be 1.




回答2:


sizeof expression returns the size required for storage of the type expression evaluates to (see http://en.cppreference.com/w/cpp/language/sizeof). In case of std::string, this contains a pointer to the data (and possibly a buffer for small strings), but not the data itself, so it doesn't (and can't) depend on string length.




回答3:


Your string variable will consist of a part most often stored on the stack, which has fixed dimensions. The size of this part is what's returned by sizeof (). Inside this fixed part is a pointer (or reference) to a part stored on the heap, which actually contain your characters and has a varying size. However the size of this part is only known at runtime, while sizeof () is computed at compile time.

You may wonder why. Things like this are both the strength and the weakness of C++. C++ is a totally different beast from e.g. languages like Python and C#. While the latter languages can produce all kinds of dynamically changing meta-data (like the size or type of a variable), the price that is paid is that they're all slow. C++, while being a bit 'spartan', can run rings around such languages. In fact most 'dynamic' languages are in fact implemented (programmed) in C/C++.



来源:https://stackoverflow.com/questions/38738037/why-sizeof-of-a-string-variable-always-return-the-same-number-even-when-conten

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!