I have a class which contains references, like:
class A {
A(B &b) : b(b) {} // constructor
B &b;
}
Sometimes b must be read-only, sometimes it is writeable. When I make a const A a(b); object, it's obvious that I want to protect the data inside it as const.
But - by accident - it's easy to make a non-const copy of the object which will make the data inside it vulnerable.
const A a(b); // b object protected here
A a_non_const(a);
a_non_const.b.non_const_function(...); // b not protected now
I think that I should somehow prevent copies of the object when it is const like this:
const A a(b);
const A a2(a); // OK!
A a_non_const(a); // Compiler error
Is this possible at all?
flaw in your code: your data isn't "protected" even with
constThe
consttype qualifier manages access to the member functions of a type as well as the access to its members. Since your memberB & bis a reference,constdoesn't do much for you here: A reference cannot be changed after initialization either way. How you access the target of that reference isn't even considered:solution with templates
Instead of (ab)using the
consttype qualifier you could add a "flag" to your type, to differentiate between cases where you need to be able to have non-const access and case where you don't:With some
std::enable_ifyou can then selectively enable / disable member functions ofAdepending on whether they need "writeable"bor not.real solution: refactor your design
BUT I'd like to highlight this comment even more:
You should probably instead consider splitting your class such that you have a
CommonAwith functionality used by both aWriteableAand aNonWriteableA(the names are terrible, but I hope you understand what I mean).