I was trying to experiment the rules of Five / Three / Zero. When Compiling my program I got a warning C26401
saying that I have to not delete pointer that I don't own and this in the line delete[] pChar_;
in the destructor function.
I agree that I have issue there specially when calling move ctor
, when I apply std::swap
when calling to the source object.
So how could I correct this issue ?
Edit: As suggested in comment, I may use std::string (Good) but I wanna know how to fix the issue without modifying the types let's say to learn that :)
using namespace std;
struct A
{
A();
A(int Int, const char* pChar);
A(const A& rhs);
A& operator=(A rhs);
A(A&& rhs);
~A();
void swap(A& rhs);
int Int_ = 0;
char *pChar_ = nullptr;
};
A::~A()
{
std::cout << "----DTOR----" << std::endl;
if (pChar_ != nullptr)
{
delete[] pChar_;
pChar_ = nullptr;
}
}
A::A(int Int, const char* pChar) :
Int_(Int), pChar_(new char[strlen(pChar) + 1])
{
strncpy_s(pChar_, strlen(pChar) + 1, pChar, _TRUNCATE);
}
A::A(const A& rhs) : A(rhs.Int_, rhs.pChar_) {}
A& A::operator=(A rhs)
{
swap(rhs);
return *this;
}
A::A(A&& rhs)
{
swap(rhs);
}
void A::swap(A& rhs)
{
std::swap(this->Int_, rhs.Int_);
std::swap(this->pChar_, rhs.pChar_);
}
int main()
{
A v1{ 1, "Hello" };
{
A v3{ std::move(v1) };
}
}