[C#] 앝은 복사와 깊은 복사 (Shallow Copy & Deep Copy)

박현민·2024년 12월 3일

유니티

목록 보기
3/6
post-thumbnail

객체를 복사할 때 데이터가 어떻게 처리되는지에 대한 개념

얕은 복사깊은 복사는 데이터를 복사할 때, 원본과 복사본이 같은 데이터를 공유하는지 또는 독립적으로 존재하는지에 따라 나뉘며, 데이터 수정 시 다른 쪽에 영향을 미치는지 차이가 있는 객체 복사의 개념이다

앝은 복사란?


앝은 복사는 객체의 참조만을 복사하여 원본과 복사본이 동일한 데이터를 공유한다.

두 변수가 동일한 메모리 주소를 가르키므로, 한쪽에서 데이터를 변경하면 다른 쪽에도 영향을 미친다.

using UnityEngine;

// PlayerData 클래스
public class PlayerData
{
	public string name;
	public int hp;
		
	public PlayerData(string name, int hp)
	{
		this.name = name;
		this.hp = hp;
	}
}

// Player 클래스
public class Player : MonoBehaviour
{
	private void Start()
	{
		PlayerData data_1 = new PlayerData("박현민", 100);
		PlayerData data_2 = data_1;
				
		Debug.Log($"이름: {data_1.name}, 체력: {data_1.hp}");
		Debug.Log($"이름: {data_2.name}, 체력: {data_2.hp}");
				
		data_2.name = "권재헌";
		data_2.hp = 150;
				
		Debug.Log($"이름: {data_1.name}, 체력: {data_1.hp}");
		Debug.Log($"이름: {data_2.name}, 체력: {data_2.hp}");
	}
}
// 출력:
// 이름: 박현민, 체력: 100
// 이름: 박현민, 체력: 100
// 이름: 권재헌, 체력: 150
// 이름: 권재헌, 체력: 150

data_2 = data_1은 새로운 객체를 생성하지 않고, data_1참조data_2복사한다.

이로 인해 data_1data_2동일한 메모리 주소를 가리키게 된다.

또한 data_2의 이름과 hp를 바꾸게 되면 동일한 메모리 주소를 가르키고 있기에 data_1data_2 의 데이터가 같이 바뀌게 된다.

깊은 복사란?


깊은 복사객체의 값 자체를 복사하여 원본과 복사본이 독립적인 메모리를 갖게 만드는 복사 방식이다.

원본의 데이터를 수정해도 복사본에는 영향이 가지 않으며 반대도 동일하다.

using UnityEngine;

// PlayerData 클래스
public class PlayerData
{
	public string name;
	public int hp;
		
	public PlayerData(string name, int hp)
	{
		this.name = name;
		this.hp = hp;
	}
}

// Player 클래스
public class Player : MonoBehaviour
{
	private Start()
	{
		PlayerData data_1 = new PlayerData("박현민", 100);
		PlayerData data_2 = new PlayerData(data_1.name, data1.hp);
				
		data_2.name = "권재헌";
		data_2.hp = 150;

		Debug.Log($"이름: {data_1.name}, 체력: {data_1.hp}");
		Debug.Log($"이름: {data_2.name}, 체력: {data_2.hp}");
	}
}
// 출력:
// 이름: 박현민, 체력: 100
// 이름: 박현민, 체력: 100
// 이름: 박현민, 체력: 100
// 이름: 권재헌, 체력: 150

data_1data_2독립된 객체이기에 data_2이름과 체력을 바꾸어도 data_1데이터는 바뀌지 않는다.

profile
자라고 있는 게임개발자

0개의 댓글