我应该返回bool还是const bool? [英] Should I return bool or const bool?

查看:185
本文介绍了我应该返回bool还是const bool?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个更好:

  bool MyClass :: someQuery()const; 

const bool MyClass :: someQuery()const;

我一直在使用'const bool',因为我确定我记得听到它是什么ints可以(例如比较运算符),但我找不到任何地方的证据,主要是因为Google和Intellisense很难帮上忙;)有人可以确认吗?



对我来说,返回const值(这不仅仅是关于布尔值)更有意义;这样可以防止临时人员被修改,这几乎总是程序员的错误。我只希望有一些东西可以备份,这样我就可以赞美const值给我的同事了:)

解决方案

所以你知道这是正确的,您只是在追求权威的声音吗?
防止临时修改临时性非常有价值。通常,您应该声明尽可能多的内容 const ,它可以保护您免受各种事故的影响,并为优化程序提供有用的提示。



您是否有Scott Meyers的有效C ++的副本?将它们指向第3项(第三版的第18页);)



给出了

  class Rational {...}; 
const Rational运算符*(const Rational& lhs,const Rational& rhs);

if((a * b)= c)//声明运算符*的返回值const导致编译器

Which is better:

bool MyClass::someQuery() const;

const bool MyClass::someQuery() const;

I've been using 'const bool' since I'm sure I remember hearing it's "what the ints do" (for e.g. comparison operators) but I can't find evidence of that anywhere, mostly due to it being difficult to Google and Intellisense not helping out any ;) Can anyone confirm that?

To me returning const values (this isn't just about bools) makes more sense; it'll prevent temporaries being modified, which is almost always going to be a programmer mistake. I just want something to back that up so I can extol returning const values to my colleagues :)

解决方案

So you know it's right, you're just after the Voice of Authority? Preventing accidental modification of temporaries is very valuable. In general, you should declare as many things as you possibly can const, it protects you from a variety of accidents and gives the optimiser useful hints.

D'you have a copy of Scott Meyers' "Effective C++" around? Point them at Item 3 (page 18 in the third edition) ;)

It gives the example of

class Rational {...};
const Rational operator* (const Rational& lhs, const Rational& rhs );

if( (a * b) = c ) // declaring operator *'s return value const causes error to be caught by compiler

这篇关于我应该返回bool还是const bool?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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