(Why) does an empty string have an address?

前端 未结 7 1371
执笔经年
执笔经年 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:54

    In C++, all classes are a specific, unchanging size. (varying by compiler and library, but specific at compile-time.) The std::string usually consists of a pointer, a length of allocation, and a length used. That's ~12 bytes, no matter how long the string is, and you have allocated std::string s on the call stack. When you display the address of the std::string, cout displays the location of the std::string in memory.

    If the string doesn't point at anything, it won't allocate any space from the heap, which is like what you're thinking. But, all c-strings end in a trailing NULL, so the c-string "" is one character long, not zero. This means when you assign the c-string "" to the std::string, the std::string allocates 1 (or more) bytes, and assigns it the value of the trailing NULL character (usually zero '\0').

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