这组例子围绕几类容易读错的 C++ 语句:跳转、列表初始化、数组所有权、流提取、条件编译和文件输入。通用示例使用 C++17;Windows、OpenCV、YOLO 相关部分明确标出依赖边界。
goto 与结构化循环
跳转到“goto 与结构化循环”goto label; 跳到同一函数内的 label:。标签需要符合标识符规则,不是任意文本;跳转还不能绕过必须完成的局部对象初始化。简单循环通常用 continue 或 break 更容易阅读。声明与跳转约束。

原图展示标签在跳转语句之前或之后的两种位置,不表示能绕过 C++ 的对象初始化和销毁规则。下面保留原来的 10~19 遍历并跳过 15,同时比较不使用 goto 的写法。
#include <cassert>#include <iostream>#include <vector>
int main() { std::vector<int> jumped; int a = 10;LOOP: do { if (a == 15) { ++a; goto LOOP; } jumped.push_back(a); ++a; } while (a < 20);
std::vector<int> structured; for (int value = 10; value < 20; ++value) { if (value == 15) continue; structured.push_back(value); } const std::vector<int> expected{10, 11, 12, 13, 14, 16, 17, 18, 19}; assert(jumped == expected && structured == expected); for (int value : jumped) std::cout << value << '\n';}花括号初始化不是一种万能构造方法
跳转到“花括号初始化不是一种万能构造方法”列表初始化从 C++11 开始提供。使用 {} 不等于“调用同一个构造函数但换个括号”:std::initializer_list 构造函数、聚合初始化和窄化检查都会影响结果。列表初始化规则。
| 情形 | 示例 | 解释 |
|---|---|---|
| 标量 | int a{10}; | 初始化为 10;int a{2.5}; 是窄化错误 |
| 容器元素 | std::vector<int> v{1, 2, 3, 4}; | 以这些元素构造 vector |
| 类成员默认值 | int value{10}; 写在类定义中 | 默认成员初始化器;不是对任意已存在成员重新初始化 |
| 选择构造函数 | Example ex{10, 20.5}; | 取决于 Example 实际有哪些构造函数 |
| 固定大小数组容器 | std::array<int, 5> arr{1, 2, 3, 4, 5}; | 五个元素;不能把它与动态 vector 的构造规则混为一谈 |
| 二元组 | std::pair<int, double> p{1, 2.5}; | 初始化两个分量 |
| 拷贝列表初始化 | std::vector<int> v = {1, 2, 3, 4}; | 仍然使用花括号;这不是容器的 emplace 操作 |
| 聚合 | Aggregate agg{10, 20.5}; | 需满足所用版本的聚合条件;不是 C++17 才首次出现的功能 |
| 默认构造 | MyClass obj{}; | 按该类型的初始化规则构造;不能保证任意用户类的所有成员自动清零 |
| 智能指针工厂 | std::make_shared<int>(10)、std::make_unique<MyClass>() | 是函数调用,不能写成 std::make_shared<int>{10} |
#include <array>#include <cassert>#include <iostream>#include <memory>#include <utility>#include <vector>
struct Aggregate { int count; double gain; };struct MyClass { int value{7}; };class Example {public: int count; double gain; Example(int c, double g) : count(c), gain(g) {}};
int main() { int a{10}; std::vector<int> values{1, 2, 3, 4}; std::vector<int> copied = {1, 2, 3, 4}; Example ex{10, 20.5}; Example parenthesized(10, 20.5); auto returned{Example(10, 20.5)}; std::array<int, 5> arr{1, 2, 3, 4, 5}; std::pair<int, double> pair{1, 2.5}; Aggregate aggregate{10, 20.5}; MyClass object{}; auto sharedInt = std::make_shared<int>(10); auto uniqueObject = std::make_unique<MyClass>(); std::vector<int> twoElements{10, 20}; std::vector<int> tenElements(10, 20); assert(a == 10 && values == copied && arr.back() == 5); assert(ex.count == 10 && ex.gain == 20.5); assert(parenthesized.gain == returned.gain && pair.second == 2.5); assert(aggregate.count == 10 && aggregate.gain == 20.5); assert(object.value == 7 && *sharedInt == 10 && uniqueObject->value == 7); assert(twoElements.size() == 2 && tenElements.size() == 10); assert(tenElements.back() == 20); std::cout << "braces: 2 elements; parentheses: 10 copies of 20\n";}原来的 auto input_image{util::RGBImageReader(input_filename, input_dims, mean, stddev)}; 可按“用一次函数/构造表达式的结果推导并初始化对象”阅读;是否能编译仍取决于该项目中 RGBImageReader 的真实声明、实参与可访问性。这里没有凭这个名字推断图像预处理语义。
数组需要数组所有权
跳转到“数组需要数组所有权”std::unique_ptr<float>{new float[10]} 类型不匹配:默认删除器会用单对象 delete 处理数组,导致未定义行为。这种代码可能编译成功,所以不能只用“编译通过”判断安全。应使用 std::unique_ptr<float[]>,或直接调用数组版 make_unique。数组 unique_ptr。
#include <cassert>#include <iostream>#include <memory>
struct Sample { inline static int alive = 0; Sample() { ++alive; } ~Sample() { --alive; }};
int main() { auto buffer = std::make_unique<float[]>(10); // 值初始化为 0 std::unique_ptr<float[]> explicitArray{new float[10]{}}; assert(buffer[9] == 0.0f && explicitArray[9] == 0.0f); buffer[0] = 1.25f; assert(buffer[0] == 1.25f); { auto samples = std::make_unique<Sample[]>(10); assert(Sample::alive == 10); } assert(Sample::alive == 0); std::cout << "array ownership: ten destructors executed\n";}智能指针本身不记录数组长度,也不检查下标;需要长度及容器操作时考虑 std::vector。异常安全还要求对象一经分配就进入清晰的所有权管理。
连续的流提取与 PPM 头
跳转到“连续的流提取与 PPM 头”input >> header.magic >> header.w >> header.h >> header.max 利用每次提取返回流引用来串联操作。必须检查流状态;中途失败可能已经修改前面的字段,可先读到临时对象,全部成功后再提交。
原例把 PPM 的 magic 定义成 int。真实 PPM 标记是文本 P6,纯文本变体为 P3;头部允许注释,宽高须为正,最大分量值须在 1~65535 内。Netpbm PPM 格式。下面只演示无注释、单行、四字段头部的严格读取,不是完整的 PPM 图像解码器。
#include <cassert>#include <initializer_list>#include <iostream>#include <sstream>#include <stdexcept>#include <string>
struct PPM { std::string magic; int w{}; int h{}; int max{};};
PPM parseHeaderLine(const std::string& line) { std::istringstream input(line); PPM candidate{}; if (!(input >> candidate.magic >> candidate.w >> candidate.h >> candidate.max)) throw std::invalid_argument("incomplete or nonnumeric header"); input >> std::ws; if (!input.eof()) throw std::invalid_argument("extra header data"); if ((candidate.magic != "P3" && candidate.magic != "P6") || candidate.w <= 0 || candidate.h <= 0 || candidate.max <= 0 || candidate.max > 65535) throw std::invalid_argument("unsupported header values"); return candidate;}
int main() { const auto header = parseHeaderLine("P6 640 480 255"); assert(header.magic == "P6" && header.w == 640 && header.h == 480 && header.max == 255); assert(parseHeaderLine("P3 1 1 65535").max == 65535); int rejected = 0; for (const char* bad : {"6 640 480 255", "P6 0 1 255", "P6 1 1 65536", "P6 1 bad 255", "P6 1 1", "P6 1 1 255 extra"}) { try { (void)parseHeaderLine(bad); } catch (const std::invalid_argument&) { ++rejected; } } assert(rejected == 6); std::cout << header.magic << ' ' << header.w << 'x' << header.h << " max=" << header.max << "; rejected=" << rejected << '\n';}文件流也可使用相同的提取操作,但需要先成功打开文件。完整 PPM 读取还要处理注释、规定的分隔字节、像素布局和数据量边界,不能用上面一个头部示例宣称已经支持整种格式。
前向声明、命令行和全局限定名
跳转到“前向声明、命令行和全局限定名”namespace Ui { class YOLOWINDOW; } 只声明类名;在看到完整定义前可以声明它的指针或引用,不能定义这种类型的普通对象、访问其成员或计算其大小。Qt 生成的 UI 类仍须在需要完整定义的源文件中包含对应头文件。
int main(int argc, char** argv) 中先检查 argc,再访问所需的 argv 元素。原片段在 assert(argc == 3) 前读取 argv[1]、argv[2],顺序不安全,且 release 构建可能关闭断言;运行参数检查应使用实际条件分支。argv[argc] 是空指针;不要把它当普通参数字符串。
::socket(...) 从全局命名空间查找 socket。:: 只处理名字查找,不负责初始化网络库、检查失败或释放句柄。下例在 Windows 上初始化 Winsock、创建一个未连接的套接字并立即关闭;不会发送数据。
// winsock-name.cpp — Windows#include <winsock2.h>#include <iostream>#ifdef _MSC_VER#pragma comment(lib, "Ws2_32.lib")#endif
int main() { WSADATA data{}; if (WSAStartup(MAKEWORD(2, 2), &data) != 0) return 1; SOCKET listener = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listener == INVALID_SOCKET) { WSACleanup(); return 2; } const int closed = closesocket(listener); const int cleaned = WSACleanup(); if (closed != 0 || cleaned != 0) return 3; std::cout << "global socket created and closed; no connection\n";}MSVC 的 #pragma comment(lib, ...) 向目标文件加入链接库记录;它不是标准 C++ 的通用链接方式。MinGW 编译上述文件需在链接命令中加 -lws2_32。原笔记同时列出的 Wsock32.lib 和 Ws2_32.lib 不能替代对实际 API 版本和构建配置的选择。comment pragma。
读懂 OpenCV 的条件编译分支
跳转到“读懂 OpenCV 的条件编译分支”原片段来自同步原语定义:外层 !defined(_M_CEE) 决定是否进入该段;启用线程支持时,cv::Mutex 对应递归互斥量,cv::AutoLock 对应作用域锁;禁用分支中的 lock()、unlock() 调用 CV_Error 报不支持,而占位 AutoLock 本身不提供同步。它不能被解释成“关闭线程也获得同样的锁”。OpenCV 同步类型文档、对应版本 utility.hpp 源码。
下面是独立的教学版本,使用自己的 DemoMutex、DemoLock,不冒充 OpenCV 头文件。分别编译普通版本和 -DDEMO_DISABLE_THREADS=1 版本,可观察两个分支。实际 OpenCV 工程须与所用版本及构建选项对应。
#include <cassert>#include <iostream>#include <mutex>#include <stdexcept>
#ifndef DEMO_DISABLE_THREADSusing DemoMutex = std::recursive_mutex;using DemoLock = std::lock_guard<DemoMutex>;#elsestruct DemoMutex { void lock() { throw std::runtime_error("thread support disabled"); } void unlock() { throw std::runtime_error("thread support disabled"); }};struct DemoLock { explicit DemoLock(DemoMutex&) {} };#endif
int main() { DemoMutex mutex;#ifndef DEMO_DISABLE_THREADS int value = 0; { DemoLock outer(mutex); DemoLock nested(mutex); ++value; } assert(value == 1); std::cout << "recursive mutex: nested scoped locking OK\n";#else { DemoLock stub(mutex); } bool rejected = false; try { mutex.lock(); } catch (const std::runtime_error&) { rejected = true; } assert(rejected); std::cout << "disabled: stub does not lock; explicit lock rejected\n";#endif}printf 的宽度、精度和类型
跳转到“printf 的宽度、精度和类型”%2.4f 的 2 是最小字段宽度,不会把 3.1416 截为两字符;.4 对这里的浮点格式表示小数点后四位。printf 的 %f 接收经默认参数提升后的 double,%lf 在此也按 double 处理;scanf 的 %f/%lf 则分别要求 float*/double*,两者不能混用。微软 printf 类型字段。
#include <cassert>#include <cstdio>#include <cstring>
int main() { double number = 3.1416; char text[32]{}; const int size = std::snprintf(text, sizeof(text), "%2.4lf", number); assert(size == 6 && std::strcmp(text, "3.1416") == 0); std::printf("%s\n", text);}文件、目录、图片与视频输入
跳转到“文件、目录、图片与视频输入”原笔记包含两条路线:std::filesystem::directory_iterator 遍历 .jpg,以及 Windows _access/_stat 和 POSIX access/stat 检查路径后再交给 YOLO。C++17 的 filesystem 可统一这里的路径分类;先检查存在也不能保证稍后打开仍成功。
下面保留两个参数 engine、input 的入口,先验证数量,再分类输入。它只收集路径和显示分类,不加载推理引擎、不解码图片、不运行模型。目录结果排序以便复现,扩展名按 ASCII 小写比较;目录扫描不递归,只收集图片,单独的视频路径则标记为视频。
#include <algorithm>#include <cctype>#include <filesystem>#include <iostream>#include <stdexcept>#include <string>#include <vector>
namespace fs = std::filesystem;struct InputFiles { std::vector<fs::path> images; bool isVideo = false; };
std::string extension(const fs::path& file) { std::string ext = file.extension().string(); std::transform(ext.begin(), ext.end(), ext.begin(), [](unsigned char ch) { return static_cast<char>(std::tolower(ch)); }); return ext;}
bool isImage(const std::string& ext) { return ext == ".jpg" || ext == ".jpeg" || ext == ".png";}
bool isVideo(const std::string& ext) { return ext == ".mp4" || ext == ".avi" || ext == ".m4v" || ext == ".mpeg" || ext == ".mov" || ext == ".mkv";}
InputFiles collect(const fs::path& input) { InputFiles result; if (fs::is_regular_file(input)) { const auto ext = extension(input); if (isImage(ext)) result.images.push_back(input); else if (isVideo(ext)) result.isVideo = true; else throw std::invalid_argument("unsupported file extension"); } else if (fs::is_directory(input)) { for (const auto& entry : fs::directory_iterator(input)) { if (entry.is_regular_file() && isImage(extension(entry.path()))) result.images.push_back(entry.path()); } std::sort(result.images.begin(), result.images.end()); } else { throw std::invalid_argument("input is not a regular file or directory"); } return result;}
int main(int argc, char** argv) { if (argc != 3) { std::cerr << "usage: input-files <engine> <input>\n"; return 2; } const fs::path engineFile = argv[1]; const fs::path input = argv[2]; try { const auto result = collect(input); std::cout << "engine argument: " << engineFile.generic_string() << '\n'; std::cout << "video=" << result.isVideo << "; images=" << result.images.size() << '\n'; for (const auto& file : result.images) std::cout << file.filename().generic_string() << '\n'; } catch (const std::exception& error) { std::cerr << "input error: " << error.what() << '\n'; return 1; }}原来的 IsPathExist、IsFile、IsFolder 分别对应“路径状态可查询”“普通文件”“目录”的判断;Windows _access、_stat 或 POSIX 对应函数各需适配平台头文件和错误码。上面的抛出式 filesystem 调用将权限、遍历等错误交给 catch 处理,没有吞成“空目录”。符号链接的跟随行为及目录在遍历中变化等情况仍须按应用约束处理。目录迭代器。
接入 OpenCV 时,可对得到的图片路径逐个调用 cv::imread(file, cv::IMREAD_COLOR),随后检查 image.empty();有扩展名不代表能解码。cv::glob(path + "/*.jpg", imagePathList) 是原稿的另一种收集方式,并不等价于上述多扩展名过滤。原 yolo(engine_file_path) 和 make_pipe(true) 属于具体推理工程,应在输入验证后按该工程的所有权、初始化和错误约定调用,不能仅凭这份语法笔记补出未提供的模型实现。
头文件声明与源文件实现
跳转到“头文件声明与源文件实现”头文件通过包含链可把声明带到当前翻译单元;只在另一个 .cpp 中包含 OpenCV,不会让主文件自动看见 cv::Mat。同样,声明 void test(); 不等于已经提供函数实现。下面保留 h2 → h1 → h0 → main 的包含关系,但用无外部依赖的函数说明编译与链接边界。
#ifndef VITALOGOS_CPP_H2_H#define VITALOGOS_CPP_H2_Hvoid test();#endif#ifndef VITALOGOS_CPP_H1_H#define VITALOGOS_CPP_H1_H#include "h2.h"#endif#ifndef VITALOGOS_CPP_H0_H#define VITALOGOS_CPP_H0_H#include "h1.h"#endif#ifndef VITALOGOS_CPP_MAIN_H#define VITALOGOS_CPP_MAIN_H#include "h0.h"#endif#include "h2.h"#include <iostream>void test() { std::cout << "test reached through header declarations\n"; }#include "main.h"int main() { test(); }编译并链接 headers/main.cpp 与 headers/h2.cpp;漏掉实现文件会发生未定义引用。原示例的 test(void){} 还缺少返回类型,应为 void test(void){}。使用 OpenCV 图像显示的主文件应自行包含需要的声明头,例如 <opencv2/imgcodecs.hpp>、<opencv2/highgui.hpp>,再正确链接相应库;成功打开窗口还取决于运行环境。不要依赖无关头文件偶然传递包含库头。源文件包含规则。
查看类型
跳转到“查看类型”typeid(output_size).name() 的结果由实现定义,适合诊断,不适合作为稳定文件格式或业务类型标识。需要在编译时证明类型时,使用 decltype 和类型特征。类型信息接口。
#include <cassert>#include <cstddef>#include <iostream>#include <type_traits>#include <typeinfo>
namespace Ui { class YOLOWINDOW; }
int main() { Ui::YOLOWINDOW* ui = nullptr; // 不需要类的完整定义 std::size_t output_size = 10; static_assert(std::is_same_v<decltype(output_size), std::size_t>); assert(ui == nullptr); const char* name = typeid(output_size).name(); assert(name != nullptr); std::cout << "implementation type name: " << name << '\n';}