sizeof continues to return 4 instead of actual size

前端 未结 5 1161
孤街浪徒
孤街浪徒 2020-12-21 04:07
#include 

using namespace std;

int main()
{
    cout << \"Do you need to encrypt or decrypt?\" << endl;
    string message;
    getline         


        
5条回答
  •  没有蜡笔的小新
    2020-12-21 04:18

    sizeof returns the size of an expression. For you, that's a std::string and for your implementation of std::string, that's four. (Probably a pointer to the buffer, internally.)

    But you see, that buffer is only pointed to by the string, it has no effect on the size of the std::string itself. You want message.size() for that, which gives you the size of the string being pointed to by that buffer pointer.

    As the string's contents change, what that buffer pointer points to changes, but the pointer itself is always the same size.


    Consider the following:

    struct foo
    {
        int bar;
    };
    

    At this point, sizeof(foo) is known; it's a compile-time constant. It's the size of an int along with any additional padding the compiler might add.

    You can let bar take on any value you want, and the size stays the same because what bar's value is has nothing to do with the type and size of bar itself.

提交回复
热议问题