[C++] 이동 생성자
Updated:
코드
#include <cstring>
#include <iostream>
using namespace std;
class Test {
private:
char *pc = nullptr;
public:
int i;
Test() {
cout << "base constructor" << endl;
this->pc = new char[32];
strcpy(this->pc, "abc");
}
Test(const Test &t) {
cout << "copy constructor" << endl;
this->pc = new char[strlen(t.pc)];
strncpy(this->pc, t.pc, strlen(pc));
}
Test(Test &&t) {
cout << "move constructor" << endl;
this->pc = t.pc;
t.pc = nullptr;
}
~Test() {
if (this->pc != nullptr) {
cout << "destructor - " << this->i << endl;
delete this->pc;
this->pc = nullptr;
}
}
};
int main() {
Test t1;
t1.i = 1;
cout << "------" << endl;
Test t2 = t1;
t2.i = 2;
cout << "------" << endl;
Test t3(move(t2));
t3.i = 3;
return 0;
}
실행 결과
base constructor
------
copy constructor
------
move constructor
destructor - 3
destructor - 1