c++ - 什么时候从函数的参数化中省略 const 是安全的?

标签 c++ constants parameter-passing function-signature

在我编写 C++ 函数时,我似乎比其他人使用了更多的 const 修饰符。

例如,我编写 Excel .xlsx 文件并为此使用 LibXL 库,而 documentation提到这样一个函数:

bool writeNum(int row, int col, double value, Format* format = 0)

我碰巧继承了这个函数,我的签名是这样的:

bool XLAPIENTRY writeNum(const int row, const int col, const double value, IFormatT<wchar_t> * format = 0);

注意行和列的 const int

问题:为 int 省略 const 是否安全? (很明显,对于指针,为指针省略 const 是危险的,但是做一些 int 的本地拷贝并不那么危险)。请注意,包含 writeNum 函数的原始 header 也没有提及 const-ing ints。为什么这里省略了 const 修饰符?

最佳答案

声明(与定义相反)中,参数上的顶级1 const 无效。可以说,它是函数的实现细节,不应该出现在声明中(它会增加困惑,但不会为调用者提供任何新信息)。

请注意 const int xint *const x是顶级常量,而 const int *const int &不是,所以后者不能有它的const删除。

定义中,您可以包含const如果它可以帮助您作为函数的实现者(所以您不会意外更改参数)。


1 “顶级常量”表示“实际上是常量”,而不是例如仅仅是一个指向 const 的指针。您可以通过 std::is_const_v 查看此属性.

例如:

  • std::is_const_v<const int> == true (const 整数)
  • std::is_const_v<const int *> == false (非 const 指向 const 整数的指针)
  • std::is_const_v<int *const> == true (const 指向非常量整数的指针)
  • std::is_const_v<const int **> == false (非常量指向非常量的指针,指向常量整数)
  • std::is_const_v<int *const *> == false (non-const 指向 const 的指针 指向非 const 整数的指针)
  • std::is_const_v<int **const> == true (const指向非常量的指针,指向非常量整数的指针)

关于c++ - 什么时候从函数的参数化中省略 const 是安全的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74094760/

相关文章:

java - JNI 返回 Signal 7 函数试图从 C++ 调用 Java

c++ - 类不存在默认构造函数但未默认传递

c++ - __declspec(dllimport/dllexport) 和继承

c++ - 如何在 C 或 C++ 中创建动态堆栈的动态数组

c++ - 如何创建访问 std::map 项的 const 成员函数

arrays - 将数组从node-postgres传递到plpgsql函数

sql - ODBC SQL Server 驱动程序 - 从字符串转换日期和/或时间时转换失败

c++ - 为什么未初始化的 const 成员在 C 中的处理方式与在 C++ 中的处理方式不同?

perl - 如何减少常量中的重复?

php - 从查询数组中获取第一个元素