Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

C++ - 자유 함수(free function) 및 주소 지정 가능한 함수(addressable function)

C++에서 free function은 클래스의 멤버를 제외한 함수를 의미합니다. 관련해서 마이크로소프트의 문서를 보면,

Functions (C++)
; https://learn.microsoft.com/en-us/cpp/cpp/functions-cpp

이런 설명이 나오는데요,

Functions that are defined at class scope are called member functions. In C++, unlike other languages, a function can also be defined at namespace scope (including the implicit global namespace). Such functions are called free functions or non-member functions; they're used extensively in the Standard Library.


쉽게 말하면, 클래스 바깥에서 정의된 전역 함수와 정적 함수를 의미합니다.




그다음 "addressable function"에 대한 설명을 다음의 문서에서 찾을 수 있습니다.

Addressing restriction
; https://en.cppreference.com/w/cpp/language/extending_std#Addressing_restriction

The behavior of a C++ program is unspecified (possibly ill-formed) if it explicitly or implicitly attempts to form a pointer, reference (for free functions and static member functions) or pointer-to-member (for non-static member functions) to a standard library function or an instantiation of a standard library function template, unless it is designated an addressable function (see below).


간단하게 말하면, "addressable function"이라고 지정한 함수만이 포인터 변수로 받을 수 있다는 것을 의미하는데요, 현재 C++ 표준 라이브러리의 경우 (위의 문서에 따라) "Designated addressable functions"에 명시한 "I/O manipulators" 관련 함수들만이 "addressable function"이라고 합니다.

뭐랄까, 이건 정책의 문제로 해석하는 편이 좋을 듯합니다. 예를 들어, 제가 mycvt라는 함수를 정의했고 그것을 "addressable function"이라고 문서에 명시했다면 다음과 같은 코드가 안전할 수 있습니다.

#include <algorithm>
#include <string>

int mycvt(int c)
{
    return c;
}

int main()
{
    std::wstring name;

    std::transform(name.begin(), name.end(), name.begin(), mycvt);
}

하지만, mycvt가 "addressable function"이 아니라고 명시했다면, 그것은 향후에 다른 오버로드를 정의할 수 있다는 입장을 취하는 것과 같습니다. 실제로 char 버전의 mycvt를 추가하면,

int mycvt(int c)
{
    return c;
}

char mycvt(char c)
{
    return c;
}

int main()
{
    std::wstring name;

    std::transform(name.begin(), name.end(), name.begin(), mycvt); // 컴파일 오류
}

이제 transform 코드는 "error C2672: 'std::transform': no matching overloaded function found" 컴파일 오류가 발생합니다. 이런 문제를 피하기 위해 "addressable function"이 아닌 함수를 저런 상황에서 써야 한다면 람다 표현을 사용할 수 있습니다.

std::transform(name.begin(), name.end(), name.begin(), [](auto c) { return mycvt(c); });

위의 코드라면, name 변수가 wstring 타입이라면 "int mycvt(int c)" 함수를 호출하고, string 타입이라면 "char mycvt(char c)" 함수를 호출합니다.




개인적으로, 위의 예제 정도는 이해가 되는데요, 반면 문서에 나온 예제는 이해가 잘 안 됩니다.

// 원본 예제에서는 std::betaf, std::riemann_zetaf를 사용했지만, 여기서는 std::tolower를 사용했습니다.
// https://en.cppreference.com/w/cpp/language/extending_std#Addressing_restriction
// Following code was well-defined in C++17, but leads to unspecified behaviors and possibly fails to compile since C++20:
#include <iostream>

int main()
{
    // by unary operator&
    auto fptr0 = &static_cast<int(&)(int)>(std::tolower);
    std::wcout << (wchar_t)fptr0('C') << "\n";

    // by std::addressof
    auto fptr1 = std::addressof(static_cast<int(&)(int)>(std::tolower));
    std::wcout << (wchar_t)fptr1('C') << "\n";

    // by function-to-pointer implicit conversion
    auto fptr2 = static_cast<int(&)(int)>(std::tolower);
    std::wcout << (wchar_t)fptr2('C') << "\n";

    // forming a reference
    auto& fref = static_cast<int(&)(int)>(std::tolower);
    std::wcout << (wchar_t)fref('C') << "\n";
}

문서에서는 위의 코드가 C++ 17에서는 컴파일이 되지만, C++ 20에선 컴파일이 되지 않을 수 있다고 합니다. 아마도 그것은 저 문서가 C++ 17 당시에 작성됐을 것이므로 향후 버전에서의 변화를 알 수 없어 그렇게 적혀 있는 것이 맞겠습니다.

하지만, 저 코드를 보면 앞서 예제를 들었던 transform + mycvt와는 다르게 static_cast 시 함수 시그니처를 함께 지정했으므로 문제될 것이 없습니다. 즉, mycvt 함수를 transform에 다음과 같이 넘긴 경우로 보면 되는데요,

{
    std::wstring name = L"TEST";
    auto fptr0 = &static_cast<int(&)(int)>(mycvt); // int mycvt(int c) 버전 선택
    std::transform(name.begin(), name.end(), name.begin(), fptr0);
}

당연히 위의 코드는 "char mycvt(char c)" 버전이 추가된다고 해도 컴파일이 잘 됩니다. 혹시, C++에 대해 잘 아시는 분이 계시다면, 왜 저 코드가 "was well-defined in C++17, but leads to unspecified behaviors and possibly fails to compile since C++20"라고 적혀 있는지 설명을 좀 덧글로 부탁드립니다. ^^




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 10/16/2024]

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

비밀번호

댓글 작성자
 



2024-10-14 09시48분
적은걸 한번 날려 먹어서 간단하게 적겠습니다.
일단 전체적으로 맞는지는 모르나? C++20에서 에러가 날거라는 부분은 맞을겁니다.

The behavior of a C++ program is unspecified (possibly ill-formed) if it explicitly or implicitly attempts to form a pointer, reference (for free functions and static member functions) or pointer-to-member (for non-static member functions) to a standard library function or an instantiation of a standard library function template, unless it is designated an addressable function (see below).
요 내용이 예제 자체가 정상적인 코드가 아니거나 권장하는 코드는 아니다. 정도로 보시면 될 것 같습니다.

Following code was well-defined in C++17, but leads to unspecified behaviors and possibly fails to compile since C++20:
그러면 왜 C++17까지는 빌드가 되지만 C++20에서 빌드가 안되는지에 대한 답이 나옵니다.
C++20이 러스트의 영향인지? 여러가지 측면에서 에러 처리가 강해졌습니다.
특히 포인터 타입 캐스팅이 까다로워 졌습니다.
예를들어 BYTE* 타입을 구조체 포인터로 캐스팅하면 에러가 납니다. C++17까지는 빌드가 됩니다.
코드에 확실하게 문제가 없다는 가정하에
MyStruct* my = static_cast<MyStruct*>(static_cast<void*>(byteArray));
이런식으로 void*로 캐스팅을 한번하면 캐스팅이 됩니다.
이승준
2024-10-14 09시50분
수정이 안되어서...
byteArray는 BYTE* 타입입니다.
bytepointer라고 쓸걸 그랬네요.
이승준
2024-10-14 08시56분
우선 답글 감사합니다. ^^

그런데, 사실 저 예제는 (g++도, msvc도 모두) C++ 20에서 컴파일이 잘 됩니다. 개인적으로 여전히 왜 저 예제가 향후 버전에서 굳이 오류가 될 수 있다고 하는 것인지 의문이 풀리지 않습니다.

가령, 제시하신 "BYTE* 타입을 구조체 포인터"로 형변환 시 에러가 날 수 있다는 점은 형식 안정성 면에서 이해가 됩니다. 하지만, 위의 예제 코드는 int tolower(int)에 대해 정확하게 int(&)(int) 함수 포인터로 형변환하는 것이 왜 "unspecified (possibly ill-formed)"로 될 수 있는 지, 그와 관련해 이론적인 설명을 좀 추가해 주신다면 ^^ 좋겠습니다.
정성태
2024-10-16 12시54분
완전히 잘못 짚었습니다. 댓글 지우고 싶네요.

검색을 해보니 https://stackoverflow.com/questions/55687044/can-i-take-the-address-of-a-function-defined-in-standard-library 요게 뜹니다.
이게 가장 맞는 설명으로 보입니다. 결론은 동작을 보증할 수 없다.
레퍼런스쪽 내용은 C++20이후에 오류 처리할 수도 있으니 쓰지 말라는 것 같습니다.
다만 C++23에서도 현재까지는 오류처리 안한거 아닌가 싶은것이 msvc미리보기에서도 빌드가 됩니다.
이승준
2024-10-16 08시54분
다시 질문을 정리할 필요가 있을 것 같습니다.

제가 본문에서 의문을 가졌던 것은, mycvt 함수가 "std::transform(name.begin(), name.end(), name.begin(), mycvt);"와 같은 코드에서 "unspecified (possibly ill-formed)" 결과인지는 알겠다는 것입니다. 하지만, "auto fptr0 = &static_cast<int(&)(int)>(std::tolower);" 같은 코드에서는 함수의 signature를 명시했는데도 왜 "unspecified (possibly ill-formed)"라고 하는 것인지를 모르겠다는 것입니다.

이승준 님의 링크에 걸린 답변을 보면, "The second call"에 해당하는 것이 제가 궁금했던 내용에 대한 답변일 듯한데요, 그런데 그 답변을 보면 int(&)(int)로 명시한 경우의 함수 포인터를 가져오는 것이 왜 "unspecified (possibly ill-formed)" 결과를 낳는 것인지 설명하지 않고 있습니다. 거기서도 그냥, tolower가 "addressable function"이 아니므로 그렇다라고만 설명할 뿐입니다.

오히려 그가 제시한 "Conclusion"의 두 번째 단락 "And [expr.unary.op]/6:"을 보면,

The address of an overloaded function can be taken only in a context that uniquely determines which version of the overloaded function is referred to.

어떤 버전의 오버로드 함수인지를 명시하면 함수의 주소를 가져올 수 있다고 하는데요, 즉, "auto fptr0 = &static_cast<int(&)(int)>(std::tolower);" 코드의 경우 int(&)(int) 버전을 명시한 경우이므로 이것은 "unspecified (possibly ill-formed)"로 취급하지 않아도 되는 것 아닐까요?
정성태
2024-10-16 09시13분
아... 제시해 주신 "https://akrzemi1.wordpress.com/2018/07/07/functions-in-std/" 글의 답변에, 다시 답변으로 달린 "Related, interesting read (though this article doesn't touch on the concept of an addressable function)" 내용에 포함된 링크 "Andrzej's C++ blog - Functions in std (https://akrzemi1.wordpress.com/2018/07/07/functions-in-std/)"에 명확한 답변이 있었습니다.

Primarily, the standard reserves the right to:
    Add new names to namespace std,
    Add new member functions to types in namespace std,
    Add new overloads to existing functions,
    Add new default arguments to functions and templates,
    Change return-types of functions in compatible ways (void to anything, numeric types in a widening fashion, etc),
    Make changes to existing interfaces in a fashion that will be backward compatible, if those interfaces are solely used to instantiate types and invoke functions. Implementation details (the primary name of a type, the implementation details for a function callable) may not be depended upon.
        For example, we may change implementation details for standard function templates so that those become callable function objects. If user code only invokes that callable, the behavior is unchanged.

위의 내용에 따라, 단순히 overload 정도만이 아니라 "new default arguments"를 가지는 변경도 포함할 수 있기 때문에, 원래는 다음과 같은 코드로 컴파일이 되었겠지만,

int mycvt(int c)
{
    return c;
}

int main()
{
    auto fptr0 = &static_cast<int(&)(int)>(mycvt);
}

이후 버전에서 다음과 같이 mycvt를 변경하게 되면,

int mycvt(int c, bool ascii = true) { ... }

더 이상 컴파일이 되지 않습니다.
정성태

... 61  62  63  64  65  66  67  68  69  70  71  72  73  [74]  75  ...
NoWriterDateCnt.TitleFile(s)
12086정성태12/20/201920915디버깅 기술: 144. windbg - Marshal.FreeHGlobal에서 발생한 덤프 분석 사례
12085정성태12/20/201918887오류 유형: 586. iisreset - The data is invalid. (2147942413, 8007000d) 오류 발생 - 두 번째 이야기 [1]
12084정성태12/19/201919319디버깅 기술: 143. windbg/sos - Hashtable의 buckets 배열 내용을 모두 덤프하는 방법 (do_hashtable.py) [1]
12083정성태12/17/201922295Linux: 27. linux - lldb를 이용한 .NET Core 응용 프로그램의 메모리 덤프 분석 방법 [2]
12082정성태12/17/201920555오류 유형: 585. lsof: WARNING: can't stat() fuse.gvfsd-fuse file system
12081정성태12/16/201922411개발 환경 구성: 465. 로컬 PC에서 개발 중인 ASP.NET Core 웹 응용 프로그램을 다른 PC에서도 접근하는 방법 [5]
12080정성태12/16/201919573.NET Framework: 870. C# - 프로세스의 모든 핸들을 열람
12079정성태12/13/201921461오류 유형: 584. 원격 데스크톱(rdp) 환경에서 다중 또는 고용량 파일 복사 시 "Unspecified error" 오류 발생
12078정성태12/13/201921245Linux: 26. .NET Core 응용 프로그램을 위한 메모리 덤프 방법 [3]
12077정성태12/13/201920348Linux: 25. 자주 실행할 명령어 또는 초기 환경을 "~/.bashrc" 파일에 등록
12076정성태12/12/201918868디버깅 기술: 142. Linux - lldb 환경에서 sos 확장 명령어를 이용한 닷넷 프로세스 디버깅 - 배포 방법에 따른 차이
12075정성태12/11/201919669디버깅 기술: 141. Linux - lldb 환경에서 sos 확장 명령어를 이용한 닷넷 프로세스 디버깅
12074정성태12/10/201919343디버깅 기술: 140. windbg/Visual Studio - 값이 변경된 경우를 위한 정지점(BP) 설정(Data Breakpoint)
12073정성태12/10/201920875Linux: 24. Linux/C# - 실행 파일이 아닌 스크립트 형식의 명령어를 Process.Start로 실행하는 방법
12072정성태12/9/201917672오류 유형: 583. iisreset 수행 시 "No such interface supported" 오류
12071정성태12/9/201921185오류 유형: 582. 리눅스 디스크 공간 부족 및 safemode 부팅 방법
12070정성태12/9/201923114오류 유형: 581. resize2fs: Bad magic number in super-block while trying to open /dev/.../root
12069정성태12/2/201919492디버깅 기술: 139. windbg - x64 덤프 분석 시 메서드의 인자 또는 로컬 변수의 값을 확인하는 방법
12068정성태11/28/201928161디버깅 기술: 138. windbg와 Win32 API로 알아보는 Windows Heap 정보 분석 [3]파일 다운로드2
12067정성태11/27/201919567디버깅 기술: 137. 실제 사례를 통해 Debug Diagnostics 도구가 생성한 닷넷 웹 응용 프로그램의 성능 장애 보고서 설명 [1]파일 다운로드1
12066정성태11/27/201919236디버깅 기술: 136. windbg - C# PInvoke 호출 시 마샬링을 담당하는 함수 분석 - OracleCommand.ExecuteReader에서 OpsSql.Prepare2 PInvoke 호출 분석
12065정성태11/25/201917540디버깅 기술: 135. windbg - C# PInvoke 호출 시 마샬링을 담당하는 함수 분석파일 다운로드1
12064정성태11/25/201920464오류 유형: 580. HTTP Error 500.0/500.33 - ANCM In-Process Handler Load Failure
12063정성태11/21/201919390디버깅 기술: 134. windbg - RtlReportCriticalFailure로부터 parameters 정보 찾는 방법
12062정성태11/21/201918891디버깅 기술: 133. windbg - CoTaskMemFree/FreeCoTaskMem에서 발생한 덤프 분석 사례 - 두 번째 이야기
12061정성태11/20/201919329Windows: 167. CoTaskMemAlloc/CoTaskMemFree과 윈도우 Heap의 관계
... 61  62  63  64  65  66  67  68  69  70  71  72  73  [74]  75  ...