C# - string 타입은 shallow copy일까요? deep copy일까요?
이런 글이 있군요,
언어별로 살펴본 Deep Copy와 Shallow Copy
; https://www.kowanas.com/coding/2021/01/02/deep-copy%EC%99%80-shallow-copy
위의 글에서 C#의 string을 deep copy로 분류해 놓았는데요, 사실 값 형식과 참조 형식의 차이점을 분명히 안다면 shallow copy라는 것을 잘 아실 것입니다. 정말 그런지 한 번 테스트를 해볼까요?
using System;
class Program
{
public int value = 0xff;
static unsafe void Main(string[] args)
{
string a = "test is good";
string b = a;
IntPtr ptrA = GetRefAddress(a);
IntPtr ptrB = GetRefAddress(b);
Console.WriteLine($"ptrA: 0x{ptrA.ToInt64().ToString("x")}");
Console.WriteLine($"ptrB: 0x{ptrB.ToInt64().ToString("x")}");
}
private unsafe static IntPtr GetRefAddress(object pg)
{
TypedReference refA = __makeref(pg);
return **(IntPtr**)&refA;
}
}
/* 출력 결과
ptrA: 0x39f2ea8
ptrB: 0x39f2ea8
*/
보다시피 변수 a, b 모두 GC Heap의 0x39f2ea8 위치를 동일하게 가리키고 있습니다.
그런데, 사실 "언어별로 shallow copy와 deep copy"를 다룬다는 것은 좀 맞지 않습니다. 일례로
해당 글에서 C의 struct가 deep copy라고 설명하는데요. 그런데, 구조체를 다음과 같이 만든 경우가 있다면,
#include <iostream>
typedef struct tagMyStruct
{
int a;
int* pB;
} MyStruct;
int main()
{
MyStruct a = { 5, new int(5) };
MyStruct b = a;
b.a = 6;
*(b.pB) = 100;
printf("%d, %d\n", a.a, *(a.pB));
printf("%d, %d\n", b.a, *(b.pB));
}
/* 출력 결과
5, 100
6, 100
*/
아무도 MyStruct 타입이 deep copy라고 대답하는 경우는 없을 것입니다. 즉, 해당 타입의 내부 구현 코드가 deep과 shallow를 결정하는 언어도 있는 것입니다.
(
첨부 파일은 이 글의 예제 코드를 포함합니다.)
그러고 보니, 예전에 쓴 글이 하나 생각나는군요. ^^
XML Serializer를 이용한 값 복사
; https://www.sysnet.pe.kr/2/0/577
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]