在 C++ 中尽可能使用 const 吗?

2022-01-05 00:00:00 reference pointers constants keyword c++

如Effective C++一书中所述:尽可能使用const.",人们会假设这个定义:Vec3f operator+(Vec3f &other);更好地定义为 Vec3f operator+(const Vec3f &other) const; 甚至更好地定义为 const Vec3f operator+(const Vec3f &other) const;.

As stated in book Effective C++: "Use const whenever possible.", one would assume that this definition: Vec3f operator+(Vec3f &other); would be better defined as Vec3f operator+(const Vec3f &other) const; or even better as const Vec3f operator+(const Vec3f &other) const;.

或者有 5 个 const 关键字的例子:const int*const Foo(const int*const&)const;

Or an example with 5 const keywords: const int*const Foo(const int*const&)const;

当然,您应该只包含 const 可以有的地方.我问的是尽可能使用它们的好习惯吗?虽然它确实为您提供了更多错误安全代码,但它可能会变得非常混乱.或者你应该,例如,忽略指针和引用 const(除非你真的需要它),并且只在类型本身上使用它,如 const int* Foo(const int* parameter)const;,所以它最终不会太乱?

Of course, you should only include const where there can be one. What Im asking is it a good practice to use them whenever possible? While it does give you more error safe code, it can get quite messy. Or should you, for example, ignore pointer and reference const (unless you really need it), and use it only on the types itself, as in const int* Foo(const int* parameter)const;, so it doesnt end up too messy?

附加信息:http://duramecho.com/ComputerInformation/WhyHowCppConst.html

提前致谢!

推荐答案

C++ 常见问题:

如果您发现普通类型安全可以帮助您使系统正确(它做;尤其是在大型系统中),您会发现 const 是正确的也有帮助.

If you find ordinary type safety helps you get systems correct (it does; especially in large systems), you'll find const correctness helps also.

当您想确保不会意外或有意更改变量时,您应该使用 const.一些常量(全局和类静态、字符串和整数,但不是具有非平凡构造函数的变量)可以放在可执行文件的只读部分,因此如果您尝试写入它会导致分段错误.

You should use const when you want to be sure not to change variable accidentally or intentionally. Some constants (globals and class static, strings & integers, but not variables with nontrivial constructor) can be placed in read-only parts of the executable, therefore result in segmentation fault if you try to write to it.

您应该明确使用 const 作为遵循此原则的函数以及函数参数的说明符.如果您不必更改实际参数,请将其设为 const.这不会限制此类函数的可能用途,而是扩展它们,因为现在它们可能用于 const 参数和 const 对象.

You should be explicit using const as a specifier on functions that follow this principle as well as on function arguments. If you don't have to change actual argument, make it const. This doesn't limit the possible usages of such function, but extends them, because now they might be used on const arguments, and on const objects.

在声明中

const int* foo(const int* const&) const;

每个const 都意味着不同的东西,是的,显然应该使用如果需要.

every const means something different and yes, obviously it should be used if it is needed.

使用 const 可以提高程序的类型安全性.

Using const increases type-safety of your program.

C++ 常见问题:

[18.3] 我应该尝试让事情const早点"还是晚点"正确?

[18.3] Should I try to get things const correct "sooner" or "later"?

在非常、非常、非常开始时.

At the very, very, very beginning.

相关文章