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.
You could use
std::optional<int>if you really want.But
setAitself 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
ais always present thanAbeing stateful with sometimes havinga, sometimes not.