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

前端 未结 3 756
伪装坚强ぢ
伪装坚强ぢ 2021-01-26 05:23

This is a rather simple problem but is pretty confusing.

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

OUTPUT:

4
         


        
相关标签:
3条回答
  • 2021-01-26 05:57

    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.

    0 讨论(0)
  • 2021-01-26 06:07

    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.

    0 讨论(0)
  • 2021-01-26 06:17

    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++.

    0 讨论(0)
提交回复
热议问题