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

前端 未结 3 815
伪装坚强ぢ
伪装坚强ぢ 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 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++.

提交回复
热议问题