尝试打印第一个命令行参数时:
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*>
来自 argv
和 argc
.例如。在 C++20 中你会这样写:
auto args = std::span(argv, size_t(argc));
然后使用 args
而不是 argv
.
关于c++ - 使用 char** argv 时如何避免指针运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45718389/