c++ - 使用 char** argv 时如何避免指针运算

标签 c++ command-line-arguments clang++ pointer-arithmetic clang-static-analyzer

尝试打印第一个命令行参数时:

std::cout << argv[0] << std::endl;

clang-tidy 发出警告:

warning: 'do not use pointer arithmetic' from [cppcoreguidelines-pro-bounds-pointer-arithmetic]

是否有另一种方法可以在不使用指针算法的情况下使用 argv 的值?是不是通过任何合理的方法访问 char** 都必须使用指针算法?

我很欣赏有一些专门的函数来处理命令行参数,但它们对于简单地打印一个参数来说似乎太重量级了。

我使用 c++ 编写,使用 clang 编译器并使用 cmake 构建。

最佳答案

来自 clang-tidy - cppcoreguidelines-pro-bounds-pointer-arithmetic :

Pointers should only refer to single objects, and pointer arithmetic is fragile and easy to get wrong. span<T> is a bounds-checked, safe type for accessing arrays of data.

是的:

Is there an alternative way to use the values of argv without using pointer arithmetic? Isn't accessing a char** by any sensible method going to have to use pointer arithmetic?

你完全正确。然而,指南是关于隐藏指针算法,让辅助类在执行算法之前进行边界检查。你可以构造一个 span<char*>来自 argvargc .例如。在 C++20 中你会这样写:

auto args = std::span(argv, size_t(argc));

然后使用 args而不是 argv .

关于c++ - 使用 char** argv 时如何避免指针运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45718389/

相关文章:

c++ - 即使从未实例化引用变量主模板,是否也需要对其进行初始化?

C++:在子数组的数组中查找最大整数

c++ - 具有 pop_back 函数的类模板 vector 无法按预期工作

c++ - 文件作为命令行参数

c# - 如何根据命令行中的列表框选择执行单独的脚本?

c++ - 模板化类构造函数的模板实例化

c++ - 在 Linux 中创建的包含 make 文件的 Visual Studio 2015 中编译 C++ 项目

c++ - 不明确的转换为引用

matlab - 如何: MATLAB script that can get arguments from Unix command-line

c++ - 为什么我得到 "Undefined symbols ... typeinfo ... vtable"与虚拟和具体类?