C++核心准则​Con.3:默认情况下,传递参照常量的指针或引用

时间:2022-07-23
本文章向大家介绍C++核心准则​Con.3:默认情况下,传递参照常量的指针或引用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

秋英

Con.3: By default, pass pointers and references to consts

Con.3:默认情况下,传递参照常量的指针或引用

Reason(原因)

To avoid a called function unexpectedly changing the value. It's far easier to reason about programs when called functions don't modify state.

为了避免被调用的函数意外修改变量的值。当被调用的函数不会修改状态时这么做会使程序的理解更加容易。

Example(示例)

void f(char* p);        // does f modify *p? (assume it does)
void g(const char* p);  // g does not modify *p
Note(注意)

It is not inherently bad to pass a pointer or reference to non-const, but that should be done only when the called function is supposed to modify the object.

将指针或者参照传递给非常量也不是就一定不好,但是最好只有在被调用的函数会修改对象时这么做。

Note(注意)

Do not cast away const

不要执行去掉const属性的转换

Enforcement(注意)

  • Flag function that does not modify an object passed by pointer or reference to non-const
  • 如果函数没有修改非常量指针或引用参照的对象,标记它。
  • Flag a function that (using a cast) modifies an object passed by pointer or reference to const
  • 如果函数使用const类型转换修改常量指针或引用参照的对象,标记它。

原文链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#con3-by-default-pass-pointers-and-references-to-consts