在C ++中尽可能使用const? [英] Use const wherever possible in C++?

查看:240
本文介绍了在C ++中尽可能使用const?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Effective C ++ 书中所述:尽可能使用const,可以假设这个定义: Vec3f operator +(Vec3f& other); 将更好地定义为 Vec3f运算符+(const Vec3f&其他)const; 或者甚至更好地定义为 const Vec3f operator +(const Vec3f& amp; ; 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; / code>,因此它不会太乱了?

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 ++常见问题

如果您发现普通类型的安全性有助于系统正确(it
;特别是在大型系统中),您会发现 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

使用


C ++常见问题

[18.3]我尝试让 const 正确更快或稍后?

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

在非常开始。

这篇关于在C ++中尽可能使用const?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆