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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13373정성태6/19/20234399오류 유형: 865. 파이썬 - pymssql 설치 관련 오류 정리
13372정성태6/15/20233112개발 환경 구성: 682. SQL Server TLS 통신을 위해 사용되는 키 길이 확인 방법
13371정성태6/15/20233132개발 환경 구성: 681. openssl - 인증서 버전(V1 / V3)
13370정성태6/14/20233297개발 환경 구성: 680. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 - TLS 1.2 지원
13369정성태6/13/20233096개발 환경 구성: 679. PyCharm(을 비롯해 JetBrains에 속한 여타) IDE에서 내부 Window들의 탭이 없어진 경우
13368정성태6/13/20233225개발 환경 구성: 678. openssl로 생성한 인증서를 SQL Server의 암호화 인증서로 설정하는 방법
13367정성태6/10/20233333오류 유형: 864. openssl로 만든 pfx 인증서를 Windows Server 2016 이하에서 등록 시 "The password you entered is incorrect" 오류 발생
13366정성태6/10/20233131.NET Framework: 2128. C# - 윈도우 시스템에서 지원하는 암호화 목록(Cipher Suites) 나열파일 다운로드1
13365정성태6/8/20232897오류 유형: 863. MODIFY FILE encountered operating system error 112(failed to retrieve text for this error. Reason: 15105)
13364정성태6/8/20233682.NET Framework: 2127. C# - Ubuntu + Microsoft.Data.SqlClient + SQL Server 2008 R2 연결 방법 [1]
13363정성태6/7/20233243스크립트: 49. 파이썬 - "Transformers (신경망 언어모델 라이브러리) 강좌" - 1장 2절 코드 실행 결과
13362정성태6/1/20233164.NET Framework: 2126. C# - 서버 측의 요청 제어 (Microsoft.AspNetCore.RateLimiting)파일 다운로드1
13361정성태5/31/20233638오류 유형: 862. Facebook - ASP.NET/WebClient 사용 시 graph.facebook.com/me 호출에 대해 403 Forbidden 오류
13360정성태5/31/20233037오류 유형: 861. WSL/docker - failed to start shim: start failed: io.containerd.runc.v2: create new shim socket
13359정성태5/19/20233354오류 유형: 860. Docker Desktop - k8s 초기화 무한 반복한다면?
13358정성태5/17/20233662.NET Framework: 2125. C# - Semantic Kernel의 Semantic Memory 사용 예제 [1]파일 다운로드1
13357정성태5/16/20233464.NET Framework: 2124. C# - Semantic Kernel의 Planner 사용 예제파일 다운로드1
13356정성태5/15/20233769DDK: 10. Device Driver 테스트 설치 관련 오류 (Code 37, Code 31) 및 인증서 관련 정리
13355정성태5/12/20233687.NET Framework: 2123. C# - Semantic Kernel의 ChatGPT 대화 구현 [1]파일 다운로드1
13354정성태5/12/20233958.NET Framework: 2122. C# - "Use Unicode UTF-8 for worldwide language support" 설정을 한 경우, 한글 입력이 '\0' 문자로 처리
13352정성태5/12/20233569.NET Framework: 2121. C# - Semantic Kernel의 대화 문맥 유지파일 다운로드1
13351정성태5/11/20234074VS.NET IDE: 185. Visual Studio - 원격 Docker container 내에 실행 중인 응용 프로그램에 대한 디버깅 [1]
13350정성태5/11/20233323오류 유형: 859. Windows Date and Time - Unable to continue. You do not have permission to perform this task
13349정성태5/11/20233663.NET Framework: 2120. C# - Semantic Kernel의 Skill과 Function 사용 예제파일 다운로드1
13348정성태5/10/20233570.NET Framework: 2119. C# - Semantic Kernel의 "Basic Loading of the Kernel" 예제
13347정성태5/10/20233935.NET Framework: 2118. C# - Semantic Kernel의 Prompt chaining 예제파일 다운로드1
1  2  3  4  5  6  7  8  9  [10]  11  12  13  14  15  ...