성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 그냥 RSS Reader 기능과 약간의 UI 편의성 때문에 사용...
[이종효] 오래된 소프트웨어는 보안 위협이 되기도 합니다. 혹시 어떤 기능...
[정성태] @Keystroke IEEE의 문서를 소개해 주시다니... +_...
[손민수 (Keystroke)] 괜히 듀얼채널 구성할 때 한번에 같은 제품 사라고 하는 것이 아...
[정성태] 전각(Full-width)/반각(Half-width) 기능을 토...
[정성태] Vector에 대한 내용은 없습니다. Vector가 닷넷 BCL...
[orion] 글 읽고 찾아보니 디자인 타임에는 InitializeCompon...
[orion] 연휴 전에 재현 프로젝트 올리자 생각해 놓고 여의치 않아서 못 ...
[정성태] 아래의 글에 정리했으니 참고하세요. C# - Typed D...
[정성태] 간단한 재현 프로젝트라도 있을까요? 저런 식으로 설명만 해...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어</h1> <p> <a target='tab' href='https://www.sysnet.pe.kr/2/0/12814'>C# 11 문법에 대해 모두 정리</a>를 했었는데, 아래의 글을 보고 나서야,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# 11-범위 지정 키워드 ; <a target='tab' href='https://forum.dotnetdev.kr/t/c-11-bart-wullems/6166'>https://forum.dotnetdev.kr/t/c-11-bart-wullems/6166</a> </pre> <br /> scoped 예약어의 존재를 알게 되었습니다. ^^ 그래서 뒤늦게나마 이렇게 정리를 하는 것이니, 기존 C# 11 글만 보신 분은 가볍게라도 한번 읽어보시길 권장합니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 지난 글에서 <a target='tab' href='https://www.sysnet.pe.kr/2/0/13275#ref_field'>ref struct의 생성자에 ref 인자로 받는 경우 그 인스턴스를 반환한다면 무조건 오류가 발생</a>한다고 했습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > GetData(); static MyType GetData() { int n = 5; var t = new MyType(<span style='color: blue; font-weight: bold'>ref n</span>); return t; // 컴파일 오류 - error CS8352: Cannot use variable 't' in this context because it may expose referenced variables outside of their declaration scope } // 외부 어셈블리에서 정의했을 지도 모를 MyType의 생성자 구현이 어떻게 되어 있는지 알 수 없으므로! // 1. 만약 이렇게 구현되었다면 문제가 없지만, ref struct MyType { public MyType(ref int n1) { } } // 2. 이렇게 구현되었다면 문제가 될 수 있음. /* ref struct MyType { ref int n; public MyType(ref int n1) { n = ref n1; } } */ </pre> <br /> 바로 이런 경우, MyType의 생성자에 넘겨 준 ref 변수가 어떤 식으로든 생성자 이외의 스택 범위로 전달하지 않겠다는 표시를 scoped 예약어로 지정할 수 있습니다. 그래서 다음과 같이 코드를 추가하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > GetData(); static MyType GetData() { int n = 5; var t = new MyType(ref n); return t; // 정상 컴파일 } ref struct MyType { public MyType(<span style='color: blue; font-weight: bold'>scoped</span> ref int n1) { } } </pre> <br /> 다시 이전의 예제가 정상적으로 컴파일 됩니다. 실제로 저렇게 scoped를 적용하게 되면, 해당 메서드는 ref int 매개변수의 사용을 현재의 스택 프레임으로 막아버립니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > ref struct MyType { public ref int n; public MyType(<span style='color: blue; font-weight: bold'>scoped</span> ref int n1) { <span style='color: blue; font-weight: bold'>n = ref n1;</span> // 컴파일 오류 - "error CS8374: Cannot ref-assign 'n1' to 'n' because 'n1' has a narrower escape scope than 'n'." } } </pre> <br /> 따라서, MyType을 사용하는 측의 코드를 컴파일하는 입장에서는 해당 메서드에 "scoped"가 적용된 것만으로 안전하게 scope 판단을 할 수 있게 된 것입니다.<br /> <br /> 이 정도면 scoped 예약어의 느낌이 팍 오시죠? ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 또 다른 사례를 하나 볼까요? ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > C# 11–The scoped keyword ; <a target='tab' href='https://bartwullems.blogspot.com/2023/02/c-11the-scoped-keyword.html'>https://bartwullems.blogspot.com/2023/02/c-11the-scoped-keyword.html</a> </pre> <br /> 위의 글에 소개된 예제 코드를 간단하게 축약하면 다음과 같은 코드로 재현할 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > MyType instance = new MyType(); Process(instance); static void Process(MyType data) { Span<int> values = stackalloc int[10]; data.Convert(values); // 컴파일 오류 2개 // error CS8352: Cannot use variable 'values' in this context because it may expose referenced variables outside of their declaration scope // error CS8350: This combination of arguments to 'MyType.Convert(Span)' is disallowed because it may expose variables referenced by parameter 'values' outside of their declaration scope } ref struct MyType { public void Convert(Span<int> values) { } } </pre> <br /> 일면 이해가 됩니다. "data.Convert(values)" 코드를 컴파일하는 입장에서 MyType의 Convert 메서드 구현이 어떻게 되었을지 모르므로 이번에도 역시 "it may expose"로 오류를 내고 있습니다. 사실, 위의 코드상으로는 문제가 없지만, 만약 MyType이 외부 어셈블리에 다음과 같이 구현되었다면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > ref struct MyType { <span style='color: blue; font-weight: bold'>Span<int> _values;</span> public void Convert(Span<int> values) { <span style='color: blue; font-weight: bold'>_values = values;</span> } } </pre> <br /> 문제가 발생할 수 있습니다. 이런 경우에도 역시, Convert에 scoped 제약을 주면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > ref struct MyType { public void Convert(<span style='color: blue; font-weight: bold'>scoped</span> Span<int> values) { } } </pre> <br /> Convert 메서드를 호출하는 측의 코드를 처리하는 C# 컴파일러 입장에서는 "scoped"가 적용된 메서드에 전달하는 매개변수의 사용 범위를 계산할 수 있으므로 컴파일 오류 없이 진행할 수 있습니다. 게다가 실제로 scoped가 있는 상태에서는,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > ref struct MyType { Span<int> _values; public void Convert(scoped Span<int> values) { _values = values; } // 컴파일 에러 - error CS8352: Cannot use variable 'Span<int>' in this context because it may expose referenced variables outside of their declaration scope } </pre> <br /> 이렇게, ^^ 감히 범위를 넘어서려는 시도는 컴파일 에러를 발생시키기 때문에 scoped를 믿고 의지할 수 있습니다.<br /> <br /> <hr style='width: 50%' /><br /> <br /> 위의 Span 예제 코드를 Span 대신 다음과 같이 일반적인 <a target='tab' href='https://www.sysnet.pe.kr/2/0/11530'>ref struct</a>로 대체해 재현하는 것도 가능합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > MyType instance = new MyType(); Process(instance); static void Process(MyType data) { <span style='color: blue; font-weight: bold'>int n = 5;</span> IntRef refN = new IntRef(<span style='color: blue; font-weight: bold'>ref n</span>); data.<span style='color: blue; font-weight: bold'>Convert(refN)</span>; // 컴파일 오류 2개 // error CS8352: Cannot use variable 'values' in this context because it may expose referenced variables outside of their declaration scope // error CS8350: This combination of arguments to 'MyType.Convert(Span)' is disallowed because it may expose variables referenced by parameter 'values' outside of their declaration scope } ref struct MyType { IntRef _ref; public void Convert(IntRef refVar) { _ref = refVar; } // 아래의 코드로 바꾸면 컴파일 없이 진행 // public void Convert(scoped IntRef refVar) { } } ref struct IntRef { public ref int n; public IntRef(ref int n1) { n = ref n1; } } </pre> <br /> 차근차근 코드를 뜯어보시면 Span 예제와 다를 바가 없고, 왜 오류 처리를 해야만 하는지, scoped로 바꾸면 왜 괜찮은 것인지 알 수 있을 것입니다. ^^<br /> <br /> <hr style='width: 50%' /><br /> <br /> 자, 이제부턴 ^^ 딴지를 좀 걸어볼까요?<br /> <br /> 위에서 계속 다룬 예제 코드는 내부의 변수를 외부에서 접근할 수 있는 문제가 있어 그걸 막기 위해 C# 컴파일러가 분주하게 유효성 체크를 한 것입니다. 그런데, 좀 이상하지 않나요? 위에서 다룬 "MyType"은 분명히 ref struct로 값 형식입니다. 따라서 instance 변수를 Process 메서드에 전달한다고 해도 "값 복사"가 되므로 매개변수인 data에 대해 Convert 메서드를 호출한다고 해도 외부 인스턴스에 영향을 미치지 못합니다.<br /> <br /> 위의 코드가 메서드 호출이라서 헷갈릴 수 있지만, 다음과 같이 로컬 변수로 테스트하면,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > int n = 10; ref int n1 = ref n; // 외부 ref struct의 <a target='tab' href='https://www.sysnet.pe.kr/2/0/13275'>ref 필드</a>에 보관한 것으로 가정 ref int n2 = ref n1; // 외부 ref struct를 메서드의 인자로 전달한 것으로 가정 int k = 60; n2 = ref k; // 메서드의 매개변수에 대해 새롭게 ref를 지정해도, Console.WriteLine(n1); // 출력: 10, 즉 매개변수의 변경으로 외부 ref struct의 ref 필드가 변경되는 것은 아님. </pre> <br /> 지금까지의 예제에서 Process 메서드에 전달한 data 타입이 외부의 instance 변수에 아무런 영향을 끼칠 수 없다는 것을 알 수 있을 것입니다. 만약, 영향을 끼치려면 Process 메서드에 대해 다음과 같이 ref로 처리를 해야 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > MyType instance = new MyType(); Process(<span style='color: blue; font-weight: bold'>ref instance</span>); // 이렇게 전달해야만, static void Process(<span style='color: blue; font-weight: bold'>ref MyType data</span>) // Process 메서드 내부에서 data에 설정한 값이 외부 스택 프레임으로 전달할 수 있게 됨! { int n = 5; IntRef refN = new IntRef(ref n); <span style='color: blue; font-weight: bold'>data.Convert(refN);</span> // 컴파일 오류 2개 } </pre> <br /> C# 컴파일러가 제대로 구분하지 못하는 또 다른 경우가 있는데요, 심지어 외부 변수를 전달하지 않는 경우에도 여전히 컴파일 오류가 발생합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Process(); static void Process() { int n = 5; <span style='color: blue; font-weight: bold'>IntRef refN = new IntRef(ref n);</span> <span style='color: blue; font-weight: bold'>MyType data = new MyType();</span> data.Convert(refN); // 컴파일 오류 2개 } // MyType, IntRef 생략 </pre> <br /> 보는 바와 같이, 이번에는 MyType data와 IntRef refN 변수가 Process 메서드의 스택 프레임 내에 함께 존재하므로 이런 경우에도 C# 컴파일러의 오류가 발생할 필요는 없습니다. 이런 부분을 향후 C# 컴파일러에서는 개선을 할지, 아니면 제가 모르는 다른 경우의 수가 있는 것인지는 모르겠습니다. ^^<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1209
(왼쪽의 숫자를 입력해야 합니다.)