小编Min*_*Gao的帖子

默认构造的 std::string c_str() 值

std::string s1;\nstd::string s2;\nassert(strlen(s1.c_str()) == 0);\nassert(s1.c_str() == s2.c_str());\n
Run Code Online (Sandbox Code Playgroud)\n

这两个断言总是正确的吗?

\n

我使用C++11,并且我检查了标准,\xc2\xa721.4.2中的表63说:

\n
\n

data() 一个可复制的非空指针,可以添加 0

\n

大小() 0

\n

capacity() 一个未指定的值

\n
\n

我认为c_str()与 相同data()。但我对这个定义有一些疑问。

\n
    \n
  1. 是否“可以添加 0”==“必须且始终添加 0”?

    \n
  2. \n
  3. 所有默认构造的 std::string 是否共享相同的底层缓冲区?

    \n
  4. \n
\n

我在gcc上测试,这两个断言是正确的。我想知道这些对于所有编译器来说总是正确的吗?

\n

c++ stdstring

3
推荐指数
1
解决办法
310
查看次数

如何强制 g++ 内联 STL 函数

测试代码:

#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)

c++ gcc stl compiler-optimization

0
推荐指数
1
解决办法
224
查看次数

在 C++ 中将 unsigned int 转换为 int 和 long

#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。

c++

0
推荐指数
1
解决办法
87
查看次数

标签 统计

c++ ×3

compiler-optimization ×1

gcc ×1

stdstring ×1

stl ×1