I'm building a program with c , but I'm not sure if this way is right.
class A {
private:
unsigned *a;
bool checkA() {
return a != nullptr;
}
public:
A() {
this->a = nullptr;
}
void setA(unsigned a) {
this->a = new unsigned(a);
}
}
The member variable 'a' will only be set by 'setA', however in other method, I have to check if 'a' has been set. Thus I used nullptr to check if it is set.
Is this code a good practice?
I tried to change the datatype of 'a' to int and set it to -1 to notice for an uninitialized value. However I think there would be a better way to do this.
Please give me some advices.
CodePudding user response:
You could use std::optional<int>
if you really want.
But setA
itself is an anti-pattern, just set the value in the constructor, RAII is your friend, not something to actively avoid.
It is much easier to reason about the code if a
is always present than A
being stateful with sometimes having a
, sometimes not.