I am fairly new at the C/C++ pointer stuff, so I was wondering if this could cause any problems?
I got a class with a pointer array variable, which I would like to move along with the other variables in the move constructor. Can I just reasign its pointer, or is that a bad idea?
class C {
private:
char* a;
int size;
public:
C(int s)
{
size = s;
a = new char[s];
}
~C() noexcept
{
size = 0;
delete[] a;
}
C(const C& o): C(o.size)
{
std::copy(o.a, o.a + size, a);
}
C(C&& o) noexcept: size(o.size)
{
a = o.a;
o.a = nullptr;
}
C& operator=(const C& o)
{
if(this != &o)
{
char * l = new char[o.size];
size = o.size;
delete[] a;
a = l;
std::copy(o.a, o.a + size, a);
}
return *this;
}
C& operator=(C&& o) noexcept
{
if(this != &o)
{
delete[] a;
size = std::move(o.size);
a = o.a;
o.a = nullptr;
}
return *this;
}
};
Any feedback is welcome!
EDITS
- Added move & assignment operator and copy constructor for complecity sake
- Updated for full 'working' MVP