It is correct to use delete on nullptr
in classes like that or should I avoid solutions like here?
class Ar{
public:
Ar();
Ar(int n);
~Ar();
void setT(int n);
void remT(int n);
int* ptr;
};
Ar::Ar() : ptr(nullptr) {};
Ar::Ar(int n) : Ar(){
ptr = new int[n];
}
Ar::~Ar(){
delete[] ptr;
}
void Ar::setT( int n ){
delete[] ptr;
ptr = new int[n];
}
void Ar::remT( int n ){
delete[] ptr;
ptr = nullptr; // #1
}
int main(){
Ar temp;
temp.setT( 5 );
temp.remT( 5 );
return 0;
} // #2
On #2 destructor
will try delete[] ptr
, where ptr==nullptr
so will do nothing. But if instruction #1 does not exist program will crash on #2 with double free or corruption error.