r-value(오른값참조)

생성일
Aug 16, 2023 11:58 PM
태그
#include<iostream> #include<memory> using namespace std; class Pet { }; class Knight { public: Knight() { cout << "Kinght()" << endl; } // 복사 생성자. Knight(const Knight& knight) { cout << "const Knight&" << endl; } // 이동 생성자 Knight(Knight&& knight) { } ~Knight() { if (_pet) delete _pet; } //복사 대입 연산자 void operator=(const Knight& knight) { cout << "operator=(const Knight&)" << endl; //깊은 복사 ( 독립적인 객체 ) _hp = knight._hp; if(knight._pet) _pet = new Pet(*knight._pet); } //이동 대입 연산자 void operator=(Knight&& knight) noexcept { cout << "opeator=(&&Knight)" << endl; // 얕은 복사. _hp = knight._hp; _pet = knight._pet; knight._pet = nullptr; } public: int _hp = 100; Pet* _pet = nullptr; }; int main() { //원본을 유지할 필요가 없을 때 빠른 복사를 위해. Knight k2; k2._pet = new Pet(); k2._hp = 1000; // 원본은 날려도 된다 << hint를 받음 Knight k3; k3 = static_cast<Knight&&>(k2); k3 = std::move(k2); // 오른값 참조로 캐스팅 unique_ptr<Knight> uptr = make_unique<Knight>(); //소유권 이전 오른값 참조로 캐스팅 uptr2 = uptr ( error ) unique_ptr<Knight> uptr2 = std::move(uptr); }