std::string s1;\nstd::string s2;\nassert(strlen(s1.c_str()) == 0);\nassert(s1.c_str() == s2.c_str());\nRun Code Online (Sandbox Code Playgroud)\n这两个断言总是正确的吗?
\n我使用C++11,并且我检查了标准,\xc2\xa721.4.2中的表63说:
\n\n\ndata() 一个可复制的非空指针,可以添加 0
\n大小() 0
\ncapacity() 一个未指定的值
\n
我认为c_str()与 相同data()。但我对这个定义有一些疑问。
是否“可以添加 0”==“必须且始终添加 0”?
\n所有默认构造的 std::string 是否共享相同的底层缓冲区?
\n我在gcc上测试,这两个断言是正确的。我想知道这些对于所有编译器来说总是正确的吗?
\n测试代码:
#include <array>
int test(const std::array<int, 10> &arr) {
return arr[9];
}
Run Code Online (Sandbox Code Playgroud)
我要实现arr[0]像C风格数组一样高效,这意味着内联STL数组[]运算符函数。
我检查了生成汇编代码:
$ g++ --std=c++17 -c test.cpp && objdump -d -C test.o
test.o: file format elf64-x86-64
Disassembly of section .text:
0000000000000000 <test(std::array<int, 10ul> const&)>:
0: 55 push %rbp
1: 48 89 e5 mov %rsp,%rbp
4: 48 83 ec 10 sub $0x10,%rsp
8: 48 89 7d f8 mov %rdi,0xfffffffffffffff8(%rbp)
c: 48 8b 45 f8 mov 0xfffffffffffffff8(%rbp),%rax
10: be 09 00 00 00 mov $0x9,%esi
15: 48 89 …Run Code Online (Sandbox Code Playgroud) #include <iostream>
using namespace std;
void fun1(int off) {
cout << "fun1 " << off << endl;
}
void fun2(long off) {
cout << "fun2 " << off << endl;
}
int main() {
unsigned int a;
a = 50;
fun1(-a);
fun2(-a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该程序的输出:
fun1 -50
fun2 4294967246
Run Code Online (Sandbox Code Playgroud)
如果我更改unsigned int a--> unsigned long a,输出均为 -50。
这种行为有明确的定义吗?相关规则是什么?
注意:我使用64位Linux,所以int是4个字节,long是8个字节。编译器是 gcc 12。