(为什么)空字符串有地址? [英] (Why) does an empty string have an address?

查看:178
本文介绍了(为什么)空字符串有地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我猜测没有,但这样的输出显示它

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 with an address ? Do you think that should not cost any memory at all ?

推荐答案

是的,您保存在内存中的每个变量都有一个地址。至于点是什么,可能有几个:

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


  1. 你的(字面上的)字符串实际上不是空单个\0字符。为了包含它而创建的 std :: string 对象可以分配自己的字符缓冲区来保存此数据,因此它也不一定为空。

  2. 如果您使用的字符串是可变的语言(如C ++中的情况),则不能保证空字符串为空。

  3. 在面向对象语言中,没有数据关联的字符串实例仍然可以用来调用字符串类的各种实例方法。这需要在内存中有一个有效的对象实例。

  4. 空字符串和 null 字符串之间有区别。有时候,区别很重要。

  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.

这篇关于(为什么)空字符串有地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆