객체가 복사될 때는, 기존 객체를 기반으로 새로운 객체가 생성됨
객체가 복사되는 경우
객체를 pass by value 방식으로 함수의 매개변수로 전달할 대
#include <iostream>
void displayPlayer(Player p)
{
}
int main()
{
Player hero{ 0,0,1 };
displayPlayer(hero);
return 0;
}
함수에서 value의 형태로 결과를 반환할 때
#include <iostream>
Player createSuperPlayer()
{
Player anEnemy{ 1,1,1 };
return anEnemy;//반환
}
int main()
{
Player enemy;
enemy = createSuperPlayer();
return 0;
}
기존 객체를 기반으로 새로운 객체를 생성할 때
// 1
Player hero {1,1,1};
Player anotherHero = hero;//복사 생성자 호출
Player anotherHero {hero};// 객체를 생성할 때 hero를 복사해서 만들어라
// 즉, 이건 동일한 의미
////////////////////////////////
//2
Player another;
another = hero;// 대입 연산자 호출 됨
객체가 어떤 방식으로 복사될 지 정의해 주어야 함
왜 중요한가?
사용자가 복사 생성자를 구현하지 않으면 , 기본 복사 생성자가 사용
멤버 변수들의 값을 복사하여 대입하는 방식
포인터 타입의 멤버 변수가 존재할 때는 주의!
얕은 복사(shallow copy) VS 깊은 복사(deep copy)
Type :: Type ( const Type& source);
#include <iostream>
class Player
{
public:
Player(int hp, int xp)
:hp{ hp }, xp{ xp }
{
std::cout << "생성자 호출됨" << std::endl;//객체 생성시 body의 내용 출력
}
//복사 생성자
Player(const Player& source) {
std::cout << "복사 생성자 호출 됨" << std::endl;
}
void Print()
{
std::cout << hp << " " << xp << std::endl;
}
private:
int hp;
int xp;
};
void PrintInformation(Player p) {
p.Print();
}
int main()
{
Player p{ 10,2 };//객체 생성
PrintInformation(p);// 객체 p를 PrintInformation의 매개변수로 복사해야 함
// 복사 생성자 호출 됨
return 0;
}
Player(const Player& other)
: x { other.x} , y { other.y } , speed{ other.speed }{
}
Player( const Player& other)
{
x = other.x ;
y = other.y;
speed = other.speed;
}
Player(const Player& other)
{
memcpy(this, &other, sizeof(other));
}
위에서 말한 매개변수 p에 제대로 값이 들어가 있음
#include <iostream>
class Player
{
public:
Player(int hp, int xp)
:hp{ hp }, xp{ xp }
{
std::cout << "생성자 호출됨" << std::endl;//객체 생성시 body의 내용 출력
}
//복사 생성자
Player(const Player& other)
:hp{ other.hp } , xp{ other.xp }
{
std::cout << "복사 생성자 호출 됨" << std::endl;
}
void Print()
{
std::cout << hp << " " << xp << std::endl;
}
private:
int hp;
int xp;
};
void PrintInformation(Player p)
{
p.Print();
}
int main()
{
Player p{ 10,2 };//객체 생성
PrintInformation(p);// 객체 p를 PrintInformation의 매개변수로 복사해야 함
// 복사 생성자 호출 됨
return 0;
}