02-现代C++基础语法

02 - 现代 C++ 基础语法

本篇回答的问题:

  • int main() 那套骨架是什么?编译单元是什么?
  • int16_t、float、double 各占几个字节?为什么音频/深度学习代码爱用 float?
  • auto 会不会很慢?constexpr 和 const 差在哪?
  • 为什么现代 C++ 的初始化统一推荐 {}?
  • 范围 for 和结构化绑定怎么写?引用和指针什么时候用哪个?
  • std::string 和 std::vector 最常用的操作有哪些?

前置要求:已读第 01 篇,会用 g++ -std=c++17 -Wall -Wextra -pedantic 编译单文件程序。


1. main 函数与编译单元

每个 C++ 程序的入口都是 main 函数,操作系统加载程序后从这里开始执行。两个规定:main 是全程序唯一不用写 return 的函数(省略时默认 return 0;,0 表示成功,对应 shell 的 $?);接收命令行参数的版本是 int main(int argc, char* argv[]),等价于 Python 的 sys.argv。

编译单元(translation unit):第 01 篇四阶段里,"编译"一次处理的对象是一个 .cpp(连同它 include 进来的所有头文件),这个整体就叫一个编译单元。关键推论:每个 .cpp 是独立翻译的,互相看不见对方内部——所以跨文件调用需要头文件里的声明,跨文件共享需要链接。这就是"头文件/源文件分离"的底层原因。

提醒:不要写 using namespace std;。它把整个标准库名字倒进全局,工程一大必然撞名(你自定义的 count、data、swap)。本书全程用 std:: 前缀,多敲几个字符换永远不踩的坑。


2. 内置类型与固定宽度整型

2.1 一个历史遗留问题

int、long 的宽度是平台相关的:64 位 Linux 上 long 是 8 字节,Windows 上是 4 字节;标准只保证"不小于",没保证"恰好是"。处理 PCM 数据时这种模糊是致命的:WAV 文件里每个 16 位样本就是 16 位,你不想在某台 Windows 机器上读错。所以现代 C++ 的习惯是:涉及二进制数据、文件格式、跨平台协议时,用 <cstdint> 里的固定宽度整型——int8_t(恰好 8 位,有符号)、uint16_t(16 位无符号,uint = unsigned int 缩写)、int32_t、int64_t,宽度永远不随平台变。

2.2 为什么音频/神经网络爱用 float

类型 宽度 典型用途
int16_t 2 字节 WAV/PCM 原始样本(16 bit 音频的事实标准)
float 4 字节 音频处理、模型权重、特征(mel 谱)的主力类型
double 8 字节 精度要求高但性能不敏感的计算

偏爱 float 的三个原因:① 省一半内存/带宽——相比 double,权重和音频缓冲的占用、搬运时间直接减半,而推理对内存带宽非常敏感;② 硬件原生支持——CPU 的 SIMD 指令一条算多个 float,GPU 张量核心更为低精度浮点而生;③ 精度够用——样本归一化到 [-1, 1],float 约 7 位有效数字绰绰有余。

惯例:落盘的原始 PCM 是 int16_t,进模型/进 DSP 流程马上转 float(通常除以 32768 归一化)。whisper.cpp 读 wav 后干的第一个转换就是这个。

完整示例:类型、宽度与 auto

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// types.cpp
#include <cmath> // std::log10 / std::fabs
#include <cstdint> // int8_t / int16_t / int32_t / int64_t
#include <cstdio>

constexpr int kSampleRate = 16000; // 编译期常量:可直接用于数组大小
const double kPi = 3.14159265358979; // 运行期只读,也可以是编译期常量

int main() {
// 固定宽度整型:宽度不随平台改变
int16_t pcm_sample = -12345; // 16 位 PCM 整数样本(WAV 文件里的样子)
int32_t pcm_rate = kSampleRate; // 采样率
std::printf("pcm_sample=%d, rate=%d\n", pcm_sample, pcm_rate);

// 浮点:音频/神经网络的世界
float normalized = pcm_sample / 32768.0f; // 归一化到 [-1, 1]
double db = 20.0 * std::log10(std::fabs(normalized)); // 需要 <cmath>
std::printf("normalized=%f, db=%f\n", normalized, db);

// 各类型在 64 位 Linux 上的宽度(单位:字节)
std::printf("char=%zu short=%zu int=%zu long=%zu float=%zu double=%zu\n",
sizeof(char), sizeof(short), sizeof(int),
sizeof(long), sizeof(float), sizeof(double));

// auto:让编译器替你写出右边那个啰嗦的类型
auto n_samples = kSampleRate * 2; // int
auto gain = 0.5f; // float
std::printf("n_samples=%d, gain=%f\n", n_samples, gain);
return 0;
}
1
g++ -std=c++17 -Wall -Wextra -pedantic -o test types.cpp && ./test

预期输出:

1
2
3
4
pcm_sample=-12345, rate=16000
normalized=-0.376740, db=-8.479177
char=1 short=2 int=4 long=8 float=4 double=8
n_samples=32000, gain=0.500000

(宽度列是 64 位 Linux 的结果;重点看 short=2 而 int=4,印证了"不能想当然"。)

2.3 auto 与类型推导

auto 让编译器根据初始化表达式推导类型:auto n = 16000;(int)、auto x = 0.5f;(float,字面量带 f 才是 float,不带是 double)、auto it = samples.begin();(不用写 std::vector<float>::iterator)。

  • auto 是编译期推导,运行时零开销——它不是"动态类型",变量类型照样定死,塞别的类型照样编译错误,跟 Python 完全是两回事。
  • 经验法则:类型显而易见或太啰嗦时用 auto,类型本身是语义时写明。auto gain = 0.5f; 很清楚,但函数签名里写 float gain 更能表达契约。
  • 注意 auto x = 0.5; 推出来是 double 不是 float,混进音频热路径会莫名变慢。

3. constexpr 与 const 的区别

一句话:const 是"运行期只读",constexpr 是"编译期常量"。

1
2
const int    a = get_from_config();   // 运行时才知道值,之后不许改 —— 合法
constexpr int b = 16000; // 编译期就是 16000 —— 可以用在更多地方

constexpr 的值编译期就确定,因此能用在要求编译期常量的位置:数组大小、模板参数、static_assert。值来自运行期的 const 变量不能。工程惯例:编译期就知道的常数(采样率、帧长、增益上限)全写 constexpr,让错误在编译期而不是运行期暴露。(C++20 还有 consteval/constinit 等更细的控制,此处不展开。)


4. 初始化:为什么现代 C++ 推荐大括号

C++ 继承了 C 的写法,历史上至少有 6 种初始化形式。现代 C++ 的推荐是统一用大括号 {}:

1
2
3
4
int a{16000};                     // 单值
float buf[3]{0.1f, 0.2f, 0.3f}; // 数组
std::vector<int> v{1, 2, 3}; // 容器,元素列表
std::vector<int> w(3, 0); // 注意:圆括号是"3 个 0",大括号是"元素 3 和 0"!

大括号最大的好处是禁止窄化转换(narrowing)——编译器不许你悄悄把"放不下"的值塞进小类型:

1
2
3
int x1 = 3.14;    // 编译通过!x1 == 3,小数部分无声无息地丢了
int x2(3.14); // 同样通过,同样丢
int x3{3.14}; // 编译错误!

用大括号时编译器明确拦下:

1
2
narrowing.cpp:1:23: error: narrowing conversion of '3.14' from 'double'
to 'int' [-Wnarrowing]

音频场景里窄化很危险:int16_t 样本转 float 没问题(放大),反向把 float 塞回 int16_t 用 {} 就会被拦住,逼你显式写 static_cast<int16_t>(s * 32768.0f) 表明"我知道有截断,是故意的"。


5. 范围 for 与结构化绑定

遍历是最高频的操作,现代写法两板斧:范围 for(for (元素 : 容器))和结构化绑定(C++17 的 for (auto& [k, v] : m),一次拆出 pair/map 元素的两个成员)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// loops.cpp
#include <cstdio>
#include <map>
#include <string>
#include <vector>

int main() {
// 一段 16kHz 采样的音频帧(单位:毫秒 -> 样本数)
std::map<std::string, int> frame_table{
{"10ms", 160},
{"20ms", 320},
{"30ms", 480},
};

// 结构化绑定:一次拿到 key 和 value,比 it->first / it->second 舒服得多
for (const auto& [duration, n_samples] : frame_table) {
std::printf("%s -> %d samples\n", duration.c_str(), n_samples);
}

// 范围 for 遍历一段归一化音频,顺便做增益
std::vector<float> samples{0.25f, -0.5f, 0.75f};
for (auto& s : samples) { // auto&:要修改元素就得用引用
s *= 2.0f;
}
for (const auto& s : samples) { // 只读遍历用 const auto&
std::printf("%g ", s);
}
std::printf("\n");
return 0;
}

预期输出:

1
2
3
4
10ms -> 160 samples
20ms -> 320 samples
30ms -> 480 samples
0.5 -1 1.5

三种形态的选择口诀:for (auto& s : v) 要修改元素;for (const auto& s : v) 只读(元素大时避免拷贝,首选);for (auto s : v) 拷贝一份(小元素无所谓)。


6. 函数:默认参数、重载、内联

默认参数:给参数一个缺省值,调用方可省略(Python 的 def f(x, ref=1.0) 对应物)。重载(overload):同名函数、不同参数表,编译器按实参类型自动挑选——Python 里要靠默认值 None 加 if 模拟,C++ 是原生能力。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// funcs.cpp
#include <cmath>
#include <cstdio>
#include <string>

// 默认参数:不传就按静音 0 分贝算
double to_db(double linear, double ref = 1.0) {
return 20.0 * std::log10(linear / ref);
}

// 重载:同名函数,参数表不同。编译器按实参类型挑一个。
int clamp_sample(int v, int lo, int hi) { return v < lo ? lo : (v > hi ? hi : v); }
double clamp_sample(double v, double lo, double hi) {
return v < lo ? lo : (v > hi ? hi : v);
}

int main() {
std::printf("amp 0.5 -> %f dB\n", to_db(0.5)); // 用默认 ref=1.0
std::printf("amp 0.5 vs 0.25 -> %f dB\n", to_db(0.5, 0.25));

std::printf("clamp int: %d\n", clamp_sample(300, -100, 100));
std::printf("clamp double: %f\n", clamp_sample(-3.5, -1.0, 1.0));

std::string name = "mel";
std::printf("len=%zu\n", name.size());
return 0;
}

预期输出:

1
2
3
4
5
amp 0.5 -> -6.020600 dB
amp 0.5 vs 0.25 -> 6.020600 dB
clamp int: 100
clamp double: -1.000000
len=3

注意:重载只看参数表,返回值类型不同不构成重载。

内联一句话:inline 原意是"建议编译器把函数体展开到调用点",但现代编译器自己决定展开与否;它现行的真正含义是允许这个函数在多个编译单元里有定义而不违反 ODR(第 01 篇提过:头文件里的定义要加 inline 或干脆是模板)。记住这句就够。


7. 引用 vs 指针

两者都是"间接访问别的对象",语义差别:引用(float&)是对象的别名——必须初始化、不能为空、绑定后不能改指别人,用起来就像原变量本身;指针(float*)是存放地址的变量——可以为 nullptr、可以重新赋值、可以做指针算术,用 *p 解引用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// refptr.cpp
#include <cstdio>

// 引用:别名,必须绑定一个已存在的对象,不会为空
void boost(float& sample, float gain) {
sample *= gain; // 直接当原变量用
}

// 指针:可以为空,调用方语义是"可能没有数据"
bool try_boost(float* sample, float gain) {
if (sample == nullptr) {
return false; // 没有数据,报告失败而不是崩溃
}
*sample *= gain;
return true;
}

int main() {
float s = 0.5f;
boost(s, 2.0f); // 传变量本身
std::printf("after ref: %g\n", s); // 1

float* p = &s;
try_boost(p, 2.0f); // 传地址
std::printf("after ptr: %g\n", s); // 2

float* nothing = nullptr;
bool ok = try_boost(nothing, 2.0f); // 空指针被显式处理
std::printf("null case handled: %s\n", ok ? "yes" : "no");
return 0;
}

预期输出:

1
2
3
after ref:  1
after ptr: 2
null case handled: no

选择口诀:参数一定要有对象 → 引用(const std::string& path 是 C++ 代码里最常见的形态);"可能没有"是合法状态 → 指针并显式判空(现代 C++ 更推荐 std::optional,以后再学);需要重绑、遍历、算术 → 指针或迭代器。现代 C++ 补充:owning(拥有资源)的裸指针基本被智能指针取代(第 04 篇),裸指针从此只表示"我在看着它,但不负责它生死"。


8. std::string 与 std::vector

这两个是现代 C++ 用得最多的容器,相当于 Python 的 str 和 list——与裸数组/C 字符串最大的不同是:它们自己管内存(这是第 03 篇 RAII 思想的头号正面案例)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// strvec.cpp
#include <cstdio>
#include <string>
#include <vector>

int main() {
// ---- std::string:会自己管理内存的字符串 ----
std::string path = "/models/";
path += "whisper"; // 拼接
path.append("/encoder.onnx"); // 也可以用 append
std::printf("path=%s, size=%zu, substr=%s\n",
path.c_str(), path.size(), path.substr(1, 6).c_str());
std::printf("contains encoder? %d\n", path.find("encoder") != std::string::npos);

// ---- std::vector:会自己管理内存的动态数组 ----
std::vector<float> ring; // 空的样本缓冲
ring.push_back(0.5f); // 追加元素,容量自动增长
ring.push_back(-0.25f);
ring.push_back(0.75f);
std::printf("size=%zu, front=%g, back=%g\n",
ring.size(), ring.front(), ring.back());

ring[1] = 0.0f; // 下标访问(不检查越界!)
std::printf("second=%g\n", ring.at(1)); // at() 会检查越界并抛异常

ring.resize(5, 0.0f); // 补零到 5 个样本,相当于静音填充
for (const auto& s : ring) {
std::printf("%g ", s);
}
std::printf("\n");
return 0;
}

预期输出:

1
2
3
4
5
path=/models/whisper/encoder.onnx, size=28, substr=models
contains encoder? 1
size=3, front=0.5, back=0.75
second=0
0.5 0 0.75 0 0

常用操作速查——string:+=/append 拼接、size()、substr(pos, n) 截取、find 查找(找不到返回 npos)、c_str() 转 C 风格 const char*(喂给 fopen 等 C 接口用)。vector:push_back 尾插、size()、v[i](不查越界)、v.at(i)(查越界,失败抛异常)、front()/back()、resize 改长度、data() 拿底层裸指针(传给 C API 用)、clear()。

性能提示:提前知道大小时先 reserve(n) 或直接 resize(n),避免 push_back 反复扩容拷贝——推理引擎里预分配输入输出缓冲是惯例。


常见坑

  1. 0.5 是 double,0.5f 才是 float:auto x = 0.5; 推出 double,混进 float 热路径会莫名变慢。
  2. v[i] 不检查越界:越界读垃圾、越界写坏内存且默认不报错(第 01 篇 ASan 一节见过现场)。要安全检查用 at()。
  3. for (auto s : v) 手滑漏了 &:想改元素结果改了副本,程序"看起来对但没效果"。
  4. v{3, 0} vs v(3, 0):前者两个元素 {3, 0},后者 3 个 0。差一个字符,天壤之别。
  5. int 和 size() 比较:size() 是无符号类型,配 int i 会吃警告(第 01 篇的 warn_demo),极端情况下负数下标变成巨大正数。
  6. 默认参数只能声明一次(通常放头文件的声明处);重载 + 默认参数别组合到两个重载对一个调用"都匹配",否则报 ambiguous。

小结

  • 一个 .cpp + 展开的头文件 = 一个编译单元;跨文件靠声明 + 链接协作。
  • 二进制/跨平台数据用 <cstdint> 固定宽度整型;推理热路径用 float;PCM 进模型前的 int16_t → float 归一化是行业惯例。
  • auto 是编译期推导、零开销;已知常数用 constexpr 优于 const。初始化统一 {},它禁止窄化转换。
  • 遍历:for (const auto& x : v) 只读首选,for (auto& x : v) 要改元素,结构化绑定 for (auto& [k, v] : m) 拆 pair。
  • 引用=别名(必非空),指针=地址(可为空);"一定有"用引用,"可能没有"用指针。
  • std::string/std::vector 自动管理内存,是 RAII 的第一个直觉来源。

自测题

  1. int16_t 和 int 的本质区别?读 16-bit WAV 样本用哪个?
  2. 为什么模型权重用 float 而不是 double?两个理由。
  3. int a = 3.14; 和 int b{3.14}; 各发生什么?
  4. constexpr int kFrame = 480; 和 const int kFrame = get_len(); 各能不能定义数组 float buf[kFrame]?
  5. 写一个范围 for:把 std::vector<float> samples 每个样本乘 0.5,再只读打印。
  6. void f(std::string path) 和 void f(const std::string& path) 对调用方各意味着什么?
答案
  1. int16_t 保证恰好 16 位、平台无关;int 只保证"至少 16 位"且随平台变。读 WAV 用 int16_t。
  2. ① 内存和带宽省一半,模型尺寸与吞吐直接受益;② CPU SIMD/GPU 张量核心对 float 有原生优化。(或:归一化后范围小,~7 位有效数字够用。)
  3. 第一行编译通过但发生窄化,a == 3,小数悄悄丢失;第二行编译错误——大括号初始化禁止窄化转换,逼你显式 static_cast。
  4. constexpr 那行可以(编译期常量);const 那行不可以(标准 C++):值运行期才确定。工程上用 std::vector 解决。
  5. 1
    2
    for (auto& s : samples) { s *= 0.5f; }
    for (const auto& s : samples) { std::printf("%g ", s); }
    要点:改元素必须 auto&;只读用 const auto&。
  6. 前者按值拷贝一个新 string(有拷贝开销);后者零拷贝且承诺不修改。"只读传入大对象"的标准姿势是 const T&。