gpt4 book ai didi

c++ - 在 C++ 中尽可能使用 const?

转载 作者:可可西里 更新时间:2023-11-01 16:38:12 24 4
gpt4 key购买 nike

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

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

当然,您应该只在可能存在的地方包含const。我问的是尽可能使用它们是一种好习惯吗?虽然它确实为您提供了更多错误安全代码,但它可能会变得非常困惑。或者,例如,您是否应该忽略指针和引用 const(除非您确实需要它),并仅在类型本身上使用它,如 const int* Foo(const int* parameter)const; ,这样它就不会变得太乱了吗?

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

提前致谢!

最佳答案

C++ FAQ:

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。一些常量(全局和静态类、字符串和整数,但不是具有非平凡构造函数的变量)可以放置在可执行文件的只读部分,因此如果您尝试写入它会导致段错误。

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

在声明中

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

每个 const 都有不同的含义,是的,显然如果需要应该使用它。

总结

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

C++ FAQ:

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

At the very, very, very beginning.

关于c++ - 在 C++ 中尽可能使用 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22285773/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com