(Why) does an empty string have an address?

前端 未结 7 1490
执笔经年
执笔经年 2021-02-19 14:19

I guessed no, but this output of something like this shows it does

string s=\"\";
cout<<&s;

what is the point of having empty string

7条回答
  •  独厮守ぢ
    2021-02-19 14:48

    Yes, every variable that you keep in memory has an address. As for what the "point" is, there may be several:

    1. Your (literal) string is not actually "empty", it contains a single '\0' character. The std::string object that is created to contain it may allocate its own character buffer for holding this data, so it is not necessarily empty either.
    2. If you are using a language in which strings are mutable (as is the case in C++), then there is no guarantee that an empty string will remain empty.
    3. In an object-oriented language, a string instance with no data associated with it can still be used to call various instance methods on the string class. This requires a valid object instance in memory.
    4. There is a difference between an empty string and a null string. Sometimes the distinction can be important.

    And yes, I very much agree with the implementation of the language that an "empty" variable should still exist in and consume memory. In an object-oriented language an instance of an object is more than just the data that it stores, and there's nothing wrong with having an instance of an object that is not currently storing any actual data.

提交回复
热议问题