It there a need to declare const instance of a class with all attributes const?

本小妞迷上赌 提交于 2019-12-14 04:11:15

问题


This is a followup to Does a class with all attributes const need to have member function declared const as well?.

So I've a class PermutationGroup whose all attribute are const. The compiler still make the distinction between const and non-const instance:

struct Foo {
  const int bar;
  void meth();
};
int main() {
   Foo foo {2};
   foo.meth();          // correct

   const Foo cfoo {1};
   cfoo.meth();         // wrong
};

As noticed by @nosid in the referred question One cannot call a non const member function a const instance:

bla.cpp: In function ‘int main()’:
bla.cpp:10:14: error: passing ‘const Foo’ as ‘this’ argument of ‘void Foo::meth()’ discards qualifiers [-fpermissive]
    cfoo.meth();

So the question is: why is it possible to declare non const instance of a class whose attribute are all const. Is there any reasonable use of that ?


回答1:


Well, a possible reasoning on why it should be allowed to declare a non-const instance in a class whose members are all const is simply the fact that you can't write the following code:

class Foo { Foo(void) const; };

Which raises:

error: constructors may not be cv-qualified

And that means, at least one member -- the constructor, and surely the destructor -- will always be non-const.



来源:https://stackoverflow.com/questions/23449773/it-there-a-need-to-declare-const-instance-of-a-class-with-all-attributes-const

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!