I am with doubt regarding clean code/coding style, the doubt is, when should I use the keyword const
in C++ constructor parameters. For example, consider the following class:
class A {
public:
B& b;
explicit A (const B& b_): b(b_) {}
};
In this code, I want to initialize the reference b
from the class A
, and at the same time, I want to express that the reference passed as a parameter to the class A
constructor will not be used to change the values of the object b_
. However, the presented code will not compile, and the compiler will present the message:
"error: binding reference of type ‘B&’ to ‘const B’ discards qualifiers"
I know I can use the keyword const
in the b
class attribute, however, it will make the attribute constant, and I do not want to impose this constraint over the attribute. So, I would like to know what should I do in this situation.
I want to express that the reference passed as a parameter to the class A constructor will not be used to change the values of the object b_.
But that's not true. The reference passed to A
's constructor can be modified. Not necessarily by A
's constructor directly, but by whatever other member functions of A
which modify the object.
If a function takes a parameter by const&
, the caller of that function has the right to expect that the object will not be modified by that function or by any process dependent on that function's execution. Such as initializing a reference member in a constructor which can be accessed after that constructor's execution.
What you should do is not lie to the user. A dependent result of A
's constructor is that the parameter passed to it may be modified. So it should be a non-const
reference.
Equally importantly, the act of creating an A
fundamentally depends on the given object continuing to exist after the constructor exits. Since a const&
parameter can be bound to a temporary, it would be very easy for someone to call your constructor like this A a(B{})
; a
after this statement references an object that has been destroyed. If your function took a non-const
reference, this would be a compile error.