问题
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