Is it good to use a const reference field as a readonly getter in C++ classes?
I mean, does this code meet good practices?
class check{
private:
int _x;
public:
const int& x = _x;
void setX(int v){
_x = v;
}
};
It is working very much like C# properties, IMHO, and very easy and clean in class usage code:
check s;
int i;
std::cin >> i;
s.setX(i);
std::cout << s.x << '\n';
s.setX(7);
// s.x = i; // Error
std::cout<<s.x<<'\n';
The readonly keyword is a modifier that can be used in four contexts: In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class.
But const (int&) is a reference int& that is const , meaning that the reference itself cannot be modified.
Technically speaking, there are no const references. A reference is not an object, so we cannot make a reference itself const. Indeed, because there is no way to make a reference refer to a different object, in some sense all references are const.
- const references allow you to specify that the data referred to won't be changed. A const reference is actually a reference to const. A reference is inherently const, so when we say const reference, it is not a reference that can not be changed, rather it's a reference to const.
do this code meet good practices?
Not really, since it introduces unnecessary complexity and space overhead.
Moreover, you wouldn't be able to perform runtime checks and/or assertions, regardless of the value being accessed.
Furthermore, what happens with the lifetime and semantics?
Try assigning one check
in your code to another and see what happens. The assignment is ill-formed because the class is non-assignable. You should provide a copy and move constructor to take care of the reference, so that it won't refer to the old object's data member.
Better use _x
directly and have a straightforward inline getter function.
PS: C#-like properties in native C++?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With