变量的声明引入名字,初始化为对象建立初始状态,后续语句才会读取或修改它。读一个声明时,应分别判断类型、作用域、链接和存储期;“在 main 外”不能直接推出“所有函数都能访问”。本文示例使用 C++17。
名字可见与对象存活是两件事
跳转到“名字可见与对象存活是两件事”| 情形 | 名字通常在哪里可用 | 初始化与存储期 |
|---|---|---|
| 命名空间作用域的普通变量 | 声明可见的范围;跨源文件需要合适的声明和链接 | 静态存储期;区分静态初始化和动态初始化 |
命名空间作用域的 static 变量 | 名字具有内部链接,限同一翻译单元 | 仍为静态存储期 |
| 块内普通局部变量 | 从声明处到所在块结束 | 执行到声明时初始化,正常离开块时销毁 |
块内 static 变量 | 名字仍只在所在块可见 | 静态存储期;需要动态初始化时,首次执行到声明才初始化 |
静态初始化包括零初始化和常量初始化,发生在动态初始化之前。不能据此断言所有全局构造函数都在 main 前完成,也不能断言局部静态对象在第一次调用之前已经构造。C++11 起,局部静态对象的首次初始化有并发保证,随后对其可变状态的读写仍需同步。静态初始化规则、块内声明规则。
下面观察局部静态初始化次数及两种局部变量的差别。
#include <cassert>#include <iostream>
int initializationCount = 0;static int fileValue; // 静态存储期的 int 被零初始化
int nextValue() { static int persistent = [] { ++initializationCount; return 0; }(); int local = 0; ++local; assert(local == 1); return ++persistent;}
int main() { assert(fileValue == 0 && initializationCount == 0); assert(nextValue() == 1); assert(nextValue() == 2); assert(initializationCount == 1); std::cout << "local=1 each call; static=1,2; initialized once\n";}对象寿命与“栈区、数据区”这样的实现术语也要区分。正常离开作用域会析构自动对象;直接调用 std::exit 不会替调用点所在作用域完成自动对象的栈展开。资源清理应依靠明确的对象所有权与正常控制流,不能笼统依赖“程序退出会释放一切”。
类型大小:先看语言保证,再看目标平台
跳转到“类型大小:先看语言保证,再看目标平台”sizeof(T) 的单位是 C++ 字节,sizeof(char) == 1,每字节位数由 CHAR_BIT 给出,至少为 8。下表的“常见字节数”以 8 位字节为前提,不是所有平台的保证。char 是否有符号由实现决定,不能固定写成 −128~127。基本类型规则。
| 类型 | 标准保证或含义 | 常见字节数与范围提示 |
|---|---|---|
bool | 两个值:false、true | 常见 1 字节;大小由实现决定 |
char | 独立字符类型,符号性由实现决定 | 1 字节;查 numeric_limits<char> |
signed char / unsigned char | 至少 8 位;无符号算术按模计算 | 常见 8 位补码实现中分别为 −128~127、0~255 |
short / unsigned short | 至少 16 位 | 常见 2 字节;无符号 16 位时为 0~65535 |
int / unsigned int | 至少 16 位 | 常见 4 字节;32 位补码实现中有符号为 −2147483648~2147483647 |
long / unsigned long | 至少 32 位 | Windows 64 位通常仍为 4;LP64 平台通常为 8 |
long long / unsigned long long | 至少 64 位 | 常见 8 字节;64 位无符号最大值为 18446744073709551615 |
sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long)。C++17 尚不统一要求有符号整数采用二进制补码,表中的常见范围不能替代实现查询。不能仅按“32 位/64 位系统”推导每种类型:Windows 的 LLP64 与许多 Unix 系统的 LP64 在 long 上不同。微软文档也将 32 位、64 位编译器的 long 列为 4 字节。Microsoft 类型范围。
| 字符类型 | 用途与边界 |
|---|---|
wchar_t | 实现定义的宽字符类型;常见大小为 2 或 4 字节,符号性也不能写死 |
char16_t | 表示 UTF-16 代码单元,底层类型为 uint_least16_t;一个字符可能需要两个代码单元 |
char32_t | 表示 UTF-32 代码单元,底层类型为 uint_least32_t;类型可表示值不全是合法 Unicode 标量值 |
| 浮点类型 | 常见实现 | 查阅方式 |
|---|---|---|
float | 常见 IEEE 754 binary32,4 字节,最大有限值约 3.4×10³⁸ | numeric_limits<float>::max() |
double | 常见 binary64,8 字节,最大有限值约 1.8×10³⁰⁸ | numeric_limits<double>::max() |
long double | 可能与 double 相同,也可能提供更大精度;存储大小还受填充影响 | 查 sizeof、digits、max(),不能统一写成 10/12/16 字节 |
对浮点数,min() 是最小正的正规值,lowest() 才是最小有限值;is_iec559 可用于查询相应实现属性。原来的编辑器内部 command: 链接不属于类型说明,已改为普通类型名。
<cstdint> 类型 | 含义 | 是否始终提供 |
|---|---|---|
int8_t / uint8_t | 恰好 8 位的有符号/无符号整数 | 可选,要求实现存在对应类型 |
int16_t / uint16_t | 恰好 16 位 | 可选 |
int32_t / uint32_t | 恰好 32 位 | 可选 |
int64_t / uint64_t | 恰好 64 位 | 可选 |
intmax_t / uintmax_t | 能表示任意有符号/无符号整数类型值的整数类型 | 提供;大小不能固定为 8 字节 |
存在的无符号 N 位精确宽度类型取值为 0~2ᴺ−1,对应有符号类型为 −2ᴺ⁻¹~2ᴺ⁻¹−1。字节数仍须结合 CHAR_BIT 判断。<cstdint> 概要。
| 其他类型 | 正确用途 |
|---|---|
std::size_t | sizeof 的无符号结果类型;不能据此保证至少与 unsigned int 一样宽 |
std::ptrdiff_t | 同一数组内指针相减的有符号结果类型;结果必须能够表示 |
std::intptr_t / std::uintptr_t | 可选的整数类型,用于相应的指针/整数往返;与大小端没有这种定义关系 |
void | 无值类型;不能定义 void 对象,也不能使用标准 C++ 的 sizeof(void) |
| 指针 | 大小依实现;不能把“所有指针都是 4 或 8 字节”写成语言保证 |
| 数组 | 连续的同类型元素;完整数组的大小为元素数乘 sizeof(元素类型) |
下面直接查询当前编译目标。它不会把某次输出当作跨平台常量。
#include <cassert>#include <climits>#include <cstddef>#include <cstdint>#include <iostream>#include <limits>#include <type_traits>
template<class T>void show(const char* name) { std::cout << name << " bytes=" << sizeof(T); if constexpr (std::is_integral_v<T>) { if constexpr (std::is_signed_v<T>) { std::cout << " min=" << static_cast<std::intmax_t>(std::numeric_limits<T>::lowest()) << " max=" << static_cast<std::intmax_t>(std::numeric_limits<T>::max()); } else { std::cout << " min=0 max=" << static_cast<std::uintmax_t>(std::numeric_limits<T>::max()); } } else { std::cout << " lowest=" << std::numeric_limits<T>::lowest() << " max=" << std::numeric_limits<T>::max(); } std::cout << '\n';}
int main() { static_assert(sizeof(char) == 1 && CHAR_BIT >= 8); static_assert(sizeof(short) <= sizeof(int)); static_assert(sizeof(int) <= sizeof(long)); static_assert(sizeof(long) <= sizeof(long long)); std::cout << "CHAR_BIT=" << CHAR_BIT << '\n'; show<bool>("bool"); show<char>("char"); show<signed char>("signed char"); show<unsigned char>("unsigned char"); show<short>("short"); show<unsigned short>("unsigned short"); show<int>("int"); show<unsigned int>("unsigned int"); show<long>("long"); show<unsigned long>("unsigned long"); show<long long>("long long"); show<unsigned long long>("unsigned long long"); show<wchar_t>("wchar_t"); show<char16_t>("char16_t"); show<char32_t>("char32_t"); show<float>("float"); show<double>("double"); show<long double>("long double"); show<std::size_t>("size_t"); show<std::ptrdiff_t>("ptrdiff_t"); show<std::intmax_t>("intmax_t"); show<std::uintmax_t>("uintmax_t"); std::cout << "void* bytes=" << sizeof(void*) << '\n'; assert(std::numeric_limits<unsigned int>::is_modulo);}数组初始化与函数参数
跳转到“数组初始化与函数参数”原始数组长度需为合适的常量表达式;标准 C++ 不支持局部变长数组。多维数组按行存放,但不能通过越过某一行边界的指针运算来遍历下一行。给出初始化列表后,未显式提供的标量元素会被值初始化;完全没有初始化器的自动 int 数组不能直接读取。数组声明、聚合初始化。
#include <cassert>#include <cstddef>#include <iostream>#include <iterator>
void fill(int values[], std::size_t count) { // 参数调整为 int* for (std::size_t i = 0; i < count; ++i) values[i] = 7;}
template<std::size_t N>constexpr std::size_t extent(const int (&)[N]) { return N; }
int main() { int eight[3 + 5]{}; int full[5] = {0, 1, 2, 3, 4}; int inferred[] = {0, 1, 2, 3, 4}; int rows[3][4] = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}; int flat[3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int inferredRows[][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; int partial[5] = {0, 1}; int firstColumn[3][4] = {{1}, {5}, {9}}; int sparse[3][4] = {{1}, {}, {0, 0, 11}}; int zeros[5] = {0}; int* pointers[3] = {nullptr}; static_assert(extent(full) == 5 && std::size(eight) == 8); static_assert(sizeof(rows) == 12 * sizeof(int)); assert(rows[2][3] == 12 && flat[2][3] == 12 && inferredRows[2][3] == 12); assert(partial[4] == 0 && firstColumn[1][1] == 0 && sparse[2][2] == 11); assert(zeros[4] == 0 && pointers[2] == nullptr && inferred[4] == 4); fill(full, std::size(full)); assert(full[0] == 7 && full[4] == 7); std::cout << "arrays: full, partial, zero, rows, pointer initialization OK\n";}普通数组形参不会携带长度;使用指针时应同时传长度,或用数组引用、容器,C++20 还可用 std::span。这里的 extent 通过数组引用保留长度。
结构体指针与函数指针别名
跳转到“结构体指针与函数指针别名”struct Sample { int channel; double value; }; 将字段组合成对象,Sample* 是指向这种对象的指针,大小和字段间填充由实现决定。原笔记放在“结构体指针”下的 typedef void (*KeyFunction)(WORD, int); 实际定义的是函数指针类型别名,不是结构体,也不是一个指针变量。WORD 是外部平台类型;完整可运行的回调示例见关键字:typedef。
枚举:类型、作用域与遍历
跳转到“枚举:类型、作用域与遍历”| 特性 | enum | enum class |
|---|---|---|
| 整数转换 | 可进行相应整数提升/转换 | 不隐式转换为整数,需显式转换 |
| 枚举项名字 | 引入外围作用域,可能是命名空间、类或块 | 默认通过枚举类型名限定 |
| 底层类型 | 可显式指定;未指定时由实现按枚举值选择 | 未显式指定时固定为 int |
| 仅声明类型 | 需写底层类型,如 enum Mode : unsigned; | enum class Color; 即可;此时底层类型已知,但枚举项尚不可用 |
| 函数参数/模板参数 | 均可使用 | 均可使用 |
| 访问控制 | 枚举项内不能插入 public: 等标签 | 同样不能;放在类内时,控制的是外层成员声明的访问 |
| 递增与遍历 | 没有通用的内建枚举递增操作 | 也没有内建 ++;显式列出允许值更稳妥 |
原表的“枚举类不能前向声明”“传统枚举不能作模板参数”“枚举类可逐项设置访问控制”均不成立。前向声明与枚举项定义的区别可对照枚举声明规则。
#include <array>#include <cassert>#include <iostream>#include <type_traits>
namespace Legacy { enum Color { RED, GREEN, BLUE }; }namespace Flags { enum Color { RED = 1, GREEN = 2, BLUE = 4 }; }enum class Color; // 固定底层类型为 int;此时不能使用 Color::REDvoid printColorName(Color color);static_assert(sizeof(Color) == sizeof(int));enum class Color { RED, GREEN, BLUE };
template<Legacy::Color C> struct LegacyTag { static constexpr auto value = C; };template<Color C> struct ColorTag { static constexpr auto value = C; };
void printColorName(Color color) { switch (color) { case Color::RED: std::cout << "Red\n"; break; case Color::GREEN: std::cout << "Green\n"; break; case Color::BLUE: std::cout << "Blue\n"; break; }}
int main() { Legacy::Color plain = Legacy::RED; if (plain == Legacy::RED) std::cout << "The color is red.\n"; std::cout << "The color code is " << static_cast<int>(Flags::GREEN) << '\n'; Color favoriteColor = Color::RED; // 枚举项定义之后才使用 assert(favoriteColor == Color::RED); static_assert(!std::is_convertible_v<Color, int>); static_assert(LegacyTag<Legacy::GREEN>::value == Legacy::GREEN); static_assert(ColorTag<Color::GREEN>::value == Color::GREEN); printColorName(Color::GREEN); constexpr std::array colors{Color::RED, Color::GREEN, Color::BLUE}; for (Color color : colors) std::cout << static_cast<int>(color) << '\n';}用同一份枚举表生成名字和语句
跳转到“用同一份枚举表生成名字和语句”宏要在展开处之前定义。生成枚举项时放未限定标识符,生成调用时再加 Color::;分号和逗号应由用途决定。原来的 ++color、在使用后才定义包装宏、把 Color::RED 直接当枚举项定义等写法不能照抄。
| 目标 | 每一项的展开 | 分隔方式 |
|---|---|---|
| 枚举项或初始化列表 | RED, 或 Color::RED, | 逗号;这些列表允许末尾逗号 |
| 独立调用语句 | processColor(Color::RED); | 每项带分号,不额外插入逗号 |
#include <array>#include <cassert>#include <iostream>
#define COLOR_ITEMS(X) X(RED) X(GREEN) X(BLUE)#define DECLARE_COLOR(name) name,enum class Color { COLOR_ITEMS(DECLARE_COLOR) };#undef DECLARE_COLOR
#define COLOR_VALUE(name) Color::name,constexpr std::array<Color, 3> colors{COLOR_ITEMS(COLOR_VALUE)};#undef COLOR_VALUE
void processColor(Color color) { std::cout << "Processing color: " << static_cast<int>(color) << '\n';}
#define PROCESS_COLOR(name) processColor(Color::name);int main() { static_assert(colors.size() == 3); assert(colors.back() == Color::BLUE); COLOR_ITEMS(PROCESS_COLOR)}#undef PROCESS_COLOR#undef COLOR_ITEMS这里保留宏生成代码的学习目的。业务代码只需遍历时,前面的 std::array 通常更直接;宏参数重复展开等限制见宏定义。