在getter中的C ++ const [英] C++ const in getter
问题描述
我仍然在学习C ++,我正在读的所有地方,我必须使用 const
无处不在(因为速度的原因,我想)。
我通常这样写我的getter方法:
const bool isReady ){
在函数后面:
return ready;但是我已经看到一些IDE以这种方式自动生成getter:
$ b
bool getReady()const {
return ready;
}
但是,写代表时,发生这个错误, code> const
成员函数'isReady' 'this'argument has type'const VideoReader',but function is not marked const
是更好的方式写一个const getter?
解决方案这两种方式之间有很大的区别:
const bool isReady()
这将返回一个
const bool
,但不保证对象不会改变它的逻辑状态bool isReady()const
这将返回一个bool,不改变你的对象的逻辑状态。所以这是你的getter。
严格地说第一个const不是必需的。返回一个const bool
没有任何意义,所以它是一个复制,所以使其const是无用的。
第二个是需要的正确性。你应该真正阅读这个,因为它不是为了速度的原因,但使你的程序更可靠。I'm still learning about C++ and I'm reading everywhere that I have to use
const
everywhere I can (for speed reason I think).I'm usually write my getter method like this:
const bool isReady() { return ready; }
But I've seen that some IDE autogenerate getter in this way:
bool getReady() const { return ready; }
But, writing delegates, it happened to me to find this error if the
const
is after the function:member function 'isReady' not viable: 'this' argument has type 'const VideoReader', but function is not marked const
So that, what is the better way to write a const getter? Do I really have to care about?
解决方案There is a huge difference between the two ways:
const bool isReady()
This will return a
const bool
but does not guarantee you that the object will not change it's logic statebool isReady() const
This will return a bool but it will not change the logic state of your object. So this is your getter.
Strictly speaken the first const it not neccessary. It makes no sense to return aconst bool
it is a copy anyway so making it const is useless.
The second one is needed for const correctness. You should really read about this as it is not for speed reasons but makes your program more reliable.这篇关于在getter中的C ++ const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!