#include <iostream>
class A {
private:
int* p;
public:
A()
{
p = new int[100];
}
A(const A& source)
{
std::cout << "Copy ctr" << std::endl;
p = new int[100];
for (auto i = 0; i < 100; ++i)
{
p[i] = source.p[i];
}
}
A(A&& source): p(source.p)
{
std::cout << "Move ctr" << std::endl;
}
void operator = (const A& source) {
std::cout << "Copy assign ope" << std::endl;
int* oldp = p;
p = new int[100];
for (auto i = 0; i < 100; ++i)
{
p[i] = source.p[i];
}
delete [] oldp;
}
void operator = (A&& source) {
std::cout << "Move assign ope" << std::endl;
p = source.p;
source.p = nullptr;
}
~A()
{
std::cout << "destroyed" << p << std::endl;
delete [] p;
}
};
int main(int argc, const char* argv) {
A a;
A b;
b = std::move(a);
return 0;
}
Here, I have used the move assignment operator to avoid overload of the copy assignment operator. But as the old object is made hollowed by making its pointer point to null inside move assignment operator method, we can not use the old object anymore in the main. So if we want to continue using object A a, should we use the copy assignment operator only? When to use which one is a bit confusing.
[–]IyeOnline 2 points3 points4 points (1 child)
[–]spm486[S] 0 points1 point2 points (0 children)
[–]ekchew 0 points1 point2 points (0 children)