Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

(시리즈 글이 2개 있습니다.)
.NET Framework: 939. C# - 전위/후위 증감 연산자에 대한 오버로딩 구현
; https://www.sysnet.pe.kr/2/0/12330

.NET Framework: 941. C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 (2)
; https://www.sysnet.pe.kr/2/0/12333




C# - 전위/후위 증감 연산자에 대한 오버로딩 구현 (2)

아래의 내용에 이어,

C# - 전위/후위 증감 연산자에 대한 오버로딩 구현
; https://www.sysnet.pe.kr/2/0/12330

덧글에서 또다시 의문을 제기했는데,

그런데 아래 내용에서 another에 value+1의 값을 넣었으면 연산 순서에 따라 연산이 된 value+1의 값이 another라는 instance에 들어가야 하는데 그렇지 않고 왜 반환되는 값은 value인 것인지 이해가 가지 않습니다.

public static Integer operator ++(Integer instance)
{
    Integer another = new Integer(instance._value + 1);
    return another;
}


어찌 보면 신기할 수 있지만, 사실 일반적인 전위/후위 원칙과 별반 다르지 않습니다. 이미 기존에도 설명했지만, 동일한 ++의 코드임에도 전/후위 표기에 따라 C# 컴파일러는 Increment/Decrement 연산자의 사용 코드를 다음과 같이 풀어서 번역합니다.

int n = 5;
int value = ++ n;

==> ++를 사용하는 측에서 다음과 같이 코드 번역

int n = 5;
n = n + 1; // 값을 증가시키고,
int value = n; // 이후에 대입

int n = 5;
int value = n ++;

==> ++를 사용하는 측에서 다음과 같이 코드 번역

int n = 5;
int value = n; // 값을 먼저 대입하고,
n = n + 1; // 이후에 증가

그러니까, 재정의된 전위/후위 연산자도 내부 코드는 같지만 사용하는 측에서 다음과 같이 번역해 버리면 그만입니다.

{
    Integer n = new Integer(5);
    Integer value = n++;
}
==>
        {
            Integer n = new Integer(5);
            Integer temp = Integer.operator ++(n);
            Integer value = n;
            n = temp;
        }

{
    Integer n = new Integer(5);
    Integer value = ++n;
}
==>
        {
            Integer n = new Integer(5);
            Integer value = Integer.operator ++(n);
            n = value;
        }

실제로 저렇게 번역이 되는지 확인하고 싶다면 IL 코드를 보면 됩니다.

.locals init (
	[0] class Integer n,
	[1] class Integer 'value',
	[2] class Integer n,
	[3] class Integer 'value'
)

/* 0x0000025C 00           */ IL_0000: nop
/* 0x0000025D 00           */ IL_0001: nop
/* 0x0000025E 1B           */ IL_0002: ldc.i4.5
/* 0x0000025F 7303000006   */ IL_0003: newobj    instance void Integer::.ctor(int32)
/* 0x00000264 0A           */ IL_0008: stloc.0
/* 0x00000265 06           */ IL_0009: ldloc.0
/* 0x00000266 25           */ IL_000A: dup
/* 0x00000267 2804000006   */ IL_000B: call      class Integer Integer::op_Increment(class Integer)
/* 0x0000026C 0A           */ IL_0010: stloc.0
/* 0x0000026D 0B           */ IL_0011: stloc.1
/* 0x0000026E 07           */ IL_0012: ldloc.1
/* 0x0000026F 280F00000A   */ IL_0013: call      void [mscorlib]System.Console::WriteLine(object)
/* 0x00000274 00           */ IL_0018: nop
/* 0x00000275 00           */ IL_0019: nop
/* 0x00000276 00           */ IL_001A: nop
/* 0x00000277 1B           */ IL_001B: ldc.i4.5
/* 0x00000278 7303000006   */ IL_001C: newobj    instance void Integer::.ctor(int32)
/* 0x0000027D 0C           */ IL_0021: stloc.2
/* 0x0000027E 08           */ IL_0022: ldloc.2
/* 0x0000027F 2804000006   */ IL_0023: call      class Integer Integer::op_Increment(class Integer)
/* 0x00000284 25           */ IL_0028: dup
/* 0x00000285 0C           */ IL_0029: stloc.2
/* 0x00000286 0D           */ IL_002A: stloc.3
/* 0x00000287 09           */ IL_002B: ldloc.3
/* 0x00000288 280F00000A   */ IL_002C: call      void [mscorlib]System.Console::WriteLine(object)
/* 0x0000028D 00           */ IL_0031: nop
/* 0x0000028E 00           */ IL_0032: nop
/* 0x0000028F 2A           */ IL_0033: ret




답변을 하다 보니, 재미있는 점이 눈에 띕니다. 전위 연산자의 경우에는 상관없지만, 후위 연산자의 경우에는, (후위 연산자가 꽤나 문제군요. ^^)

{
    Integer n = new Integer(5);
    Integer value = ++n;
}
==>
        {
            Integer n = new Integer(5);
            Integer value = Integer.operator ++(n);
            n = value;
        }

결국 같은 인스턴스가 n과 value에 들어가 참조 값이 같아집니다. 실제로 이를 다음의 코드로 테스트해볼 수 있습니다.

{
    Integer n = new Integer(5);
    Integer value = ++n;

    value.Increment(); //
    value.Increment(); // value의 값을 변경했지만,
    value.Increment(); //
    Console.WriteLine(value); // 출력 결과: 9
    Console.WriteLine(n); // 출력 결과: 9 (n의 값도 함께 변경)
}

public class Integer
{
    int _value;

    // ...[생략]...

    internal void Increment()
    {
        _value++;
    }
}

이것은 일종의 side-effect 일 수 있는데, 이런 부분을 고려한다면 연산자 오버로딩을 포함한 타입은 가능한 class보다는 struct로 구현하는 것이 권장됩니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 12/18/2020]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12377정성태10/15/202011386디버깅 기술: 172. windbg - 파일 열기 시점에 bp를 걸어 파일명 알아내는 방법(Managed/Unmanaged)
12376정성태10/15/20208120오류 유형: 669. windbg - sos의 name2ee 명령어 실행 시 "Failed to request module list." 오류
12375정성태10/15/20209484Windows: 177. 윈도우 탐색기에서 띄우는 cmd.exe 창의 디렉터리 구분 문자가 'Yen(¥)' 기호로 나오는 경우 [1]
12374정성태10/14/202014077.NET Framework: 953. C# 9.0 - (6) 함수 포인터(Function pointers) [1]파일 다운로드2
12373정성태10/14/20209373.NET Framework: 952. OpCodes.Box와 관련해 IL 형식으로 직접 코딩 시 유의할 점
12372정성태10/13/202011312.NET Framework: 951. C# 9.0 - (5) 로컬 함수에 특성 지정 가능(Attributes on local functions)파일 다운로드1
12371정성태10/13/20209982개발 환경 구성: 519. Visual Studio의 Ctrl+Shift+U (Edit.MakeUppercase) 단축키가 동작하지 않는 경우
12370정성태10/13/202010845Linux: 33. Linux - nmcli를 이용한 고정 IP 설정
12369정성태10/12/202013669Windows: 176. Raymond Chen이 한글날에 밝히는 윈도우의 한글 자모 분리 현상 [3]
12368정성태10/12/20209689오류 유형: 668. VSIX 확장 빌드 - The "GetDeploymentPathFromVsixManifest" task failed unexpectedly.
12367정성태10/12/202022456오류 유형: 667. Ubuntu - Temporary failure resolving 'kr.archive.ubuntu.com' [2]
12366정성태10/12/202011514.NET Framework: 950. C# 9.0 - (4) 원시 크기 정수(Native ints) [1]파일 다운로드1
12365정성태10/12/202010469.NET Framework: 949. C# 9.0 - (3) 람다 메서드의 매개 변수 무시(Lambda discard parameters)파일 다운로드1
12364정성태10/11/202011680.NET Framework: 948. C# 9.0 - (2) localsinit 플래그 내보내기 무시(Suppress emitting localsinit flag)파일 다운로드1
12363정성태10/11/202012590.NET Framework: 947. C# 9.0 - (1) 대상으로 형식화된 new 식(Target-typed new expressions) [2]파일 다운로드1
12362정성태10/11/20209335VS.NET IDE: 151. Visual Studio 2019에 .NET 5 rc/preview 적용하는 방법
12361정성태10/11/202010942.NET Framework: 946. C# 9.0을 위한 개발 환경 구성
12360정성태10/8/20208164오류 유형: 666. The type or namespace name '...' does not exist in the namespace 'Microsoft.VisualStudio.TestTools' (are you missing an assembly reference?)
12359정성태10/7/20209683오류 유형: 665. Windows - 재부팅 후 iSCSI 연결이 끊기는 문제
12358정성태10/7/20209692오류 유형: 664. Web Deploy 설치 시 "A newer version of Microsoft Web Deploy 3.6 was found on this machine." 오류 [3]
12357정성태10/7/20207773오류 유형: 663. 이벤트 로그 - The storage optimizer couldn't complete retrim on New Volume
12356정성태10/7/202022461오류 유형: 662. ASP.NET Core와 500.19, 500.21 오류 (0x8007000d)
12355정성태10/3/20207869오류 유형: 661. Hyper-V Linux VM의 Internal 유형의 가상 Switch에 대한 IP 연결이 되지 않는 경우
12354정성태10/2/202020699오류 유형: 660. Web Deploy (msdeploy.axd) 실행 시 오류 기록 [1]
12353정성태10/2/202010501개발 환경 구성: 518. 비주얼 스튜디오에서 IIS 웹 서버로 "Web Deploy"를 이용해 배포하는 방법
12352정성태10/2/202011008개발 환경 구성: 517. Hyper-V Internal 네트워크에 NAT을 이용한 인터넷 연결 제공
... 46  47  48  49  [50]  51  52  53  54  55  56  57  58  59  60  ...