1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| #include <iostream>
#include <cstring>
class A
{
private:
char *str;
size_t length;
public:
A() : str(0), length(0)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
}
A(char const *s)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
str=new char[std::strlen(s)+1];
length=std::strlen(s)+1;
strcpy(str, s);
}
A(A const &a)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
str=new char[a.length];
length=a.length;
std::memcpy(str, a.str, length);
}
A(A &&a)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
length=a.length;
a.length=0;
str=a.str;
a.str=0;
}
~A()
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
delete[] str;
}
A& operator=(A const &a)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
char *tmp=0;
tmp=new char[a.length];
std::memcpy(tmp, a.str, a.length);
delete[] str;
length=a.length;
str=tmp;
return *this;
}
A& operator=(A &&a)
{
std::cout << __PRETTY_FUNCTION__ << std::endl;
delete[] str;
length=a.length;
a.length=0;
str=a.str;
a.str=0;
return *this;
}
};
int main(void)
{
A a;
A b;
b="toto"; //appel de A::operator=(A &&)
a=std::move(b); //appel de A::operator=(A &&)
A c(std::move(a)); //appel de A::A(A &&);
return 0;
} |