跳转到内容
新建笔记

C++ 关键字:类型推导、对象状态与链接

关键字的含义取决于它所在的声明或表达式。本文先给出常用词的索引,再用完整程序说明 static、const、auto、new、typedef、异常和 extern。除标明 C++20 的例子外,程序使用 C++17。

关键字索引与版本边界

跳转到“关键字索引与版本边界”

原表中 andb、and_eqb、xorb、xor_eqb 末尾的 b 来自参考页面的脚注标记,不是关键字的一部分;and 对应逻辑与 &&,按位与对应 bitand。这些替代记号也没有在 C++20 被删除。size_t 则是库类型别名,不是关键字。Microsoft 关键字表及脚注。

用途关键字阅读要点
基本类型bool、char、wchar_t、char16_t、char32_t、short、int、long、signed、unsigned、float、double、voidint 默认有符号;普通 char 的符号性由实现决定;C++20 增加 char8_t
条件与循环if、else、switch、case、default、for、while、do、break、continue、gotobreak 退出最近的循环或 switch;continue 转到最近循环的下一次迭代
返回和常量值return、true、false、nullptrnullptr 自 C++11 提供,不是整数零的宏
自定义类型class、struct、union、enumclass 与 struct 的默认成员访问和默认继承访问不同
成员和访问public、protected、private、this、friend、mutable、virtual、explicit静态成员函数没有 this;mutable 成员可在 const 对象上修改;explicit 限制相应隐式转换
声明与链接static、extern、thread_local、inline、namespace、using、typedefinline 还涉及多处定义规则,不保证机器码内联;thread_local 是线程存储期
类型推导与模板auto、decltype、template、typenameC++11 的 auto 用于推导;不再把它写成 C 的存储类说明符
常量表达式与约束constexpr、static_assert;C++20 的 consteval、constinit、concept、requiresconstexpr 函数也能运行时调用;consteval 用于立即函数;constinit 约束静态/线程存储期变量的初始化,不自动使其 const
cv 限定const、volatilevolatile 不提供线程同步,也不代替原子操作
分配与释放new、delete还要区分 = delete 的禁用函数声明
查询与对齐sizeof、alignof、alignas、typeidalignof 查询类型;alignas 不能降低本来所需的对齐;typeid(...).name() 不保证固定可读字符串
显式转换static_cast、dynamic_cast、const_cast、reinterpret_cast见表达式与转换,每一种都有限制
运算符定义operator重载不能改变优先级、结合性或操作数个数
异常try、catch、throw、noexceptnoexcept 是异常契约;异常越过不抛出边界会终止程序
协程,C++20co_await、co_yield、co_return语言机制与库类型分开;std::generator 是 C++23 库设施
模块与实现相关项export、asm、registerC++20 模块可写 export module math;;汇编内容依实现;register 自 C++17 不再是存储类说明符,但仍保留为关键字

constinit 不是“仅用于局部静态变量”的词;requires 也不能随意附在普通非模板函数后。约束模板时可用 template<class T> requires (sizeof(T) > 1) void f(T);。旧的 export MyClass; 不表示导出一个类。上表不是编译器扩展词全集。

替代记号对应符号类型
and、or、not&&、||、!逻辑运算
bitand、bitor、xor、compl&、|、^、~按位运算
and_eq、or_eq、xor_eq、not_eq&=、|=、^=、!=复合赋值与不等比较

static 与 const:分清修饰对象

跳转到“static 与 const:分清修饰对象”

命名空间作用域的 static 名字有内部链接;局部 static 保留对象状态,但名字不会因此变成全局可见。类的静态成员属于类,静态成员函数没有 this,却可以通过显式提供的对象访问该类非静态成员。链接规则。

局部静态对象的动态初始化发生在首次执行到声明时,初始化的并发保证不覆盖以后的 count++。类静态数据成员通常在一个源文件定义,C++17 的 inline static 则可直接在类内定义。块内静态初始化、静态数据成员。

const 限制的是通过相应访问方式的修改。const 成员函数不能通过 this 修改普通非静态成员,但可修改 mutable 成员;也不保证它指向的其他对象不被修改。按值参数的顶层 const 只约束函数内的局部副本。

static-const.cpp
#include <cassert>
#include <iostream>
static int fileStaticVariable = 0;
static void fileStaticFunction() { ++fileStaticVariable; }
void function() {
static int count = 0;
std::cout << ++count << '\n';
}
class MyClass {
int value_ = 7;
public:
static int value;
inline static int inlineValue = 9; // C++17
int getValue() const { return value_; }
static int staticFunction(const MyClass& object) { return object.value_; }
};
int MyClass::value = 0;
class Example {
public:
static int staticVar;
const int constVar;
mutable int reads = 0;
explicit Example(int v) : constVar(v) {}
static void staticFunction() {
std::cout << "Static function called. StaticVar: " << staticVar << '\n';
}
void constFunction() const {
++reads;
std::cout << "Const function called. constVar: " << constVar << '\n';
}
};
int Example::staticVar = 10;
void printValue(const int value) { std::cout << value << '\n'; }
int main() {
function();
function();
fileStaticFunction();
assert(fileStaticVariable == 1);
MyClass object;
assert(MyClass::value == 0 && MyClass::inlineValue == 9);
assert(MyClass::staticFunction(object) == object.getValue());
const int constantValue = 10;
int value = constantValue;
int other = 20;
int* const constPtr = &value;
const int* ptrToConst = &value;
const int* const constPtrToConst = &value;
*constPtr = 11; // 地址固定,但指向的非 const 对象可改
ptrToConst = &other; // 地址可改;不能通过它修改所指值
assert(*ptrToConst == 20 && *constPtrToConst == 11);
const Example ex(5);
Example::staticFunction();
ex.constFunction();
assert(ex.reads == 1);
Example::staticVar = 20;
Example::staticFunction();
printValue(constantValue);
}

int* const 是常量指针,const int* 是指向 const 的指针,两者组合为 const int* const。指针本身与所指对象应分开检查。

用法示例结果或版本
按值推导auto copy = source;常见情形会去掉顶层 const 和引用;数组表达式也可能退化为指针
引用推导auto& alias = source;保留引用关系及所引用对象的 const
范围 forfor (auto& item : values)可修改原容器元素;写 auto item 得到副本
Lambda 对象auto square = [](int x) { return x * x; };保存编译器生成的闭包类型
返回类型推导auto add(int a, int b) { return a + b; }C++14 起可从函数体推导
decltypedecltype(source) 与 decltype((source))后者对普通左值表达式通常给出引用类型;不等同于 auto
简写函数模板auto twice(auto value) { return value + value; }C++20;这里的参数对应隐式模板参数

原来 template<class T> void func(auto value) 额外引入了独立的 T;它不会因为 value 的类型而自动推导出 T。下面用断言区分实际类型。占位类型推导。

// auto-types.cpp — C++20
#include <cassert>
#include <iostream>
#include <type_traits>
#include <vector>
auto add(int a, int b) { return a + b; }
auto twice(auto value) { return value + value; }
int main() {
const int source = 10;
auto copy = source;
auto& alias = source;
decltype(source) alsoConst = 10;
decltype((source)) reference = source;
static_assert(std::is_same_v<decltype(copy), int>);
static_assert(std::is_same_v<decltype(alias), const int&>);
static_assert(std::is_same_v<decltype(alsoConst), const int>);
static_assert(std::is_same_v<decltype(reference), const int&>);
copy = 20;
std::vector<int> values{1, 2, 3};
for (auto& item : values) item *= 2;
auto square = [](int x) { return x * x; };
assert(source == 10 && alias == 10 && alsoConst == 10 && reference == 10);
assert(values == std::vector<int>({2, 4, 6}));
assert(add(2, 3) == 5 && square(4) == 16 && twice(3) == 6);
std::cout << "copy=" << copy << "; source=" << source << "; auto and decltype OK\n";
}

new 与 delete:初始化和释放必须成对

跳转到“new 与 delete:初始化和释放必须成对”
表达式含义配对或边界
new int分配单个 int,默认初始化不可在赋值前读取该标量;最终用 delete
new int(5) / new int{5}分配并初始化为 5delete p
new int[n]分配数组,元素默认初始化delete[] p;未初始化元素不可直接读取
new int[3]()数组元素值初始化,此处全为 0delete[] p
new int[3]{1, 2, 3}数组列表初始化delete[] p
new Example(5)选择类的构造函数构造函数内部才可能委托其他构造函数
std::make_unique<T>(...)返回拥有单个对象的智能指针自动调用正确删除器
std::make_unique<T[]>(n)返回拥有数组的智能指针自动 delete[];内置标量元素值初始化

原表的 new 类型(: 初始化参数列表)、new 类型[大小](: ...) 不是合法的“委托分配”语法。委托构造写在类的构造函数初始化列表中。普通抛出型 new 分配失败通常抛出 std::bad_alloc,不应只检查空指针;构造函数也可能抛出其他异常。

allocation.cpp
#include <cassert>
#include <iostream>
#include <memory>
struct Item {
inline static int alive = 0;
int value;
Item() : Item(5) {} // 委托构造在这里
explicit Item(int v) : value(v) { ++alive; }
~Item() { --alive; }
};
int main() {
int* uninitialized = new int;
*uninitialized = 7;
assert(*uninitialized == 7);
delete uninitialized;
int* value = new int(5);
assert(*value == 5);
delete value;
int* zeros = new int[3]();
int* values = new int[3]{1, 2, 3};
assert(zeros[2] == 0 && values[2] == 3);
delete[] zeros;
delete[] values;
{
auto one = std::make_unique<Item>(9);
auto many = std::make_unique<Item[]>(3);
assert(Item::alive == 4 && one->value == 9 && many[2].value == 5);
}
assert(Item::alive == 0);
std::cout << "single and array ownership: all four Items destroyed\n";
}

这里保留裸 new 以说明配对规则;实际拥有对象时优先把生命周期交给容器或智能指针。delete nullptr 和 delete[] nullptr 可安全使用,但重复删除或混用两种删除形式会造成未定义行为。删除表达式。

typedef void (*KeyFunction)(WORD, int); 将“参数为 WORD、int,返回 void 的函数指针类型”命名为 KeyFunction。此时还没有创建指针变量。Windows 的 WORD 和虚拟键值来自相应平台头文件;以下用明确的 16 位整数及值 0x41 演示同一回调签名。

callbacks.cpp
#include <cassert>
#include <cstdint>
#include <iostream>
#include <type_traits>
using WORD = std::uint16_t; // 本例自己的别名,不冒充已包含 Windows 头文件
constexpr WORD keyA = 0x41;
typedef void (*KeyFunction)(WORD, int);
using KeyFunctionUsing = void (*)(WORD, int);
static_assert(std::is_same_v<KeyFunction, KeyFunctionUsing>);
void keyPress(WORD key, int duration) {
assert(key == keyA && duration == 100);
std::cout << "key=" << key << ", duration=" << duration << '\n';
}
int main() {
KeyFunction myKeyFunction = keyPress;
KeyFunction callbacks[] = {myKeyFunction};
callbacks[0](keyA, 100);
}

匹配的 catch 处理从 try 中传播来的异常;通常按 const 引用捕获标准异常。noexcept 表示异常不能越过该函数边界,并不禁止函数内部抛出后自己捕获,也不保证更快或“自动避免泄漏”。异常逃出不抛出函数时会调用 std::terminate,不能指望外层 catch 接住或保证所有局部析构都发生。异常规格、终止规则。

exceptions.cpp
#include <cassert>
#include <iostream>
#include <stdexcept>
struct Guard {
int& destroyed;
~Guard() { ++destroyed; }
};
int recoverLocally() noexcept {
try { throw 7; }
catch (int value) { return value; }
}
int main() {
int destroyed = 0;
try {
Guard guard{destroyed};
throw std::runtime_error("Something went wrong");
} catch (const std::runtime_error& error) {
std::cout << "Caught exception: " << error.what() << '\n';
}
assert(destroyed == 1 && recoverLocally() == 7);
static_assert(noexcept(recoverLocally()));
}

extern:头文件声明,一个源文件定义

跳转到“extern:头文件声明,一个源文件定义”

extern 不要求定义必须在“另一个文件”;它可以在同一翻译单元稍后出现。没有初始化器的 extern int globalVariable; 是声明,extern int globalVariable = 42; 则是定义。函数声明通常不必显式写 extern。

下面将原来的变量、函数、共享常量和 YOLO_SIZE 场景合成三个文件。为独立演示链接规则,Size 是本例的普通结构体;OpenCV 对应写法在后面的表中单独给出。

extern/shared.h
#ifndef VITALOGOS_CPP_SHARED_H
#define VITALOGOS_CPP_SHARED_H
struct Size { int width; int height; };
extern int globalVariable;
extern const int CONSTANT_VALUE;
extern Size YOLO_SIZE;
void someFunction();
#endif
extern/shared.cpp
#include "shared.h"
int globalVariable = 42;
const int CONSTANT_VALUE = 100; // 此前的 extern 声明使此名字保持外部链接
Size YOLO_SIZE{640, 640};
void someFunction() {
++globalVariable;
YOLO_SIZE.width = 320;
}
extern/main.cpp
#include "shared.h"
#include <cassert>
#include <iostream>
int main() {
assert(globalVariable == 42 && CONSTANT_VALUE == 100);
assert(YOLO_SIZE.width == 640 && YOLO_SIZE.height == 640);
someFunction();
assert(globalVariable == 43 && YOLO_SIZE.width == 320);
std::cout << globalVariable << ' ' << CONSTANT_VALUE << ' '
<< YOLO_SIZE.width << 'x' << YOLO_SIZE.height << '\n';
}

将两个源文件一起编译、链接,例如 g++ -std=c++17 extern/main.cpp extern/shared.cpp -o extern-demo。只编译主文件会缺少定义;把普通非 inline 全局变量的定义写入被两个源文件包含的头文件,则违反单一定义规则,通常在链接时报告重复定义。头文件保护只能防止同一翻译单元重复包含。

原 OpenCV 场景声明/定义的位置
yolowindow.h包含 <opencv2/core/types.hpp>,用头文件保护,然后写 extern cv::Size YOLO_SIZE;
yolowindow.cpp先包含上述头文件,再写 cv::Size YOLO_SIZE{640, 640};
使用它的源文件包含 yolowindow.h 后可写 cv::Size size = YOLO_SIZE;;仍需配置实际 OpenCV 依赖

上表是依赖 OpenCV 的集成说明,前三个文件的编译验证不代表 OpenCV 工程验证。C++17 也可选择在头文件放 inline cv::Size YOLO_SIZE{640, 640};。普通命名空间 const 对象默认内部链接等情况另有规则,所以“头文件每种变量定义都会造成同一种多重定义错误”不准确;需要按声明形式判断。单一定义规则。