c++ - &string 和 &string[0] 的内存地址不同?

标签 c++ string

来自 Strings in Depth ,我了解到字符串类的内存布局的确切实现不是由 C++ 标准定义的。但是为什么&string&string[0]会有不同的内存地址呢?

string variable("String Test");
cout << (void *) &variable << endl;         // 003EFE58
cout << (void *) &variable[0] << endl;      // 003EFE5C
cout << (void *) &variable[1] << endl;      // 003EFE5D
... ...

但他们确实共享相同的内容,查看:

cout << ((string)*(&variable))[0] << endl;  // 'S'
cout << *(&variable[0]) << endl;            // 'S'

谁能解释一下这是怎么回事?

最佳答案

因为一个是类实例的地址,另一个是第一个字符的地址,它通常包含在由类管理的动态分配的内存中(或者在实例本身的某个地方,在 SSO 的情况下) ).

关于c++ - &string 和 &string[0] 的内存地址不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21355731/

相关文章:

c - C 中 char 数组的奇怪行为

c++ - 强制 auto 成为循环范围内的引用类型

python - tensorflow 模型 : How to identify input/output nodes name from a proto buff file?

excel - 从用户定义函数返回 Empty 实际上返回 0

C 字符串解析和转换

java - 我想使用用户输入的字符串 ex 的前 3 个字母。 "january"结果 :"jan"

c - 为什么我的代码无法将一个字符串复制到另一个字符串?

c++ - 如何将文件夹删除到回收站

C++通过随机选择它们的元素从两个元组制作元组

c++ _vsnprintf 意外的格式字符串