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) { ... }

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

1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13784정성태10/23/20243483Linux: 95. eBPF - kprobe를 이용한 트레이스
13783정성태10/23/20243223Linux: 94. eBPF - vmlinux.h 헤더 포함하는 방법 (bpf2go에서 사용)
13782정성태10/23/20243015Linux: 93. Ubuntu 22.04 - 커널 이미지로부터 커널 함수 역어셈블
13781정성태10/22/20242919오류 유형: 930. WSL + eBPF: modprobe: FATAL: Module kheaders not found in directory
13780정성태10/22/20243131Linux: 92. WSL 2 - 커널 이미지로부터 커널 함수 역어셈블
13779정성태10/22/20243200개발 환경 구성: 729. WSL 2 - Mariner VM 커널 이미지 업데이트 방법
13778정성태10/21/20243439C/C++: 181. C/C++ - 소스코드 파일의 인코딩, 바이너리 모듈 상태의 인코딩
13777정성태10/20/20243220Windows: 265. Win32 API의 W(유니코드) 버전은 UCS-2일까요? UTF-16 인코딩일까요?
13776정성태10/19/20243289C/C++: 180. C++ - 고수준 FILE I/O 함수에서의 Unicode stream 모드(_O_WTEXT, _O_U16TEXT, _O_U8TEXT)파일 다운로드1
13775정성태10/19/20243315개발 환경 구성: 728. 윈도우 환경의 개발자를 위한 UTF-8 환경 설정
13774정성태10/18/20243124Linux: 91. Container 환경에서 출력하는 eBPF bpf_get_current_pid_tgid의 pid가 존재하지 않는 이유
13773정성태10/18/20243210Linux: 90. pid 네임스페이스 구성으로 본 WSL 2 + docker-desktop
13772정성태10/17/20243204Linux: 89. pid 네임스페이스 구성으로 본 WSL 2 배포본의 계층 관계
13771정성태10/17/20243117Linux: 88. WSL 2 리눅스 배포본 내에서의 pid 네임스페이스 구성
13770정성태10/17/20242987Linux: 87. ps + grep 조합에서 grep 명령어를 사용한 프로세스를 출력에서 제거하는 방법
13769정성태10/15/20243731Linux: 86. Golang + bpf2go를 사용한 eBPF 기본 예제파일 다운로드1
13768정성태10/15/20243264C/C++: 179. C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드파일 다운로드2
13767정성태10/14/20243033오류 유형: 929. bpftrace 수행 시 "ERROR: Could not resolve symbol: /proc/self/exe:BEGIN_trigger"
13766정성태10/14/20243074C/C++: 178. C++ - 파일에 대한 Text 모드의 "translated" 동작파일 다운로드1
13765정성태10/12/20243117오류 유형: 928. go build 시 "package maps is not in GOROOT" 오류
13764정성태10/11/20243161Linux: 85. Ubuntu - 원하는 golang 버전 설치
13763정성태10/11/20243359Linux: 84. WSL / Ubuntu 20.04 - bpftool 설치
13762정성태10/11/20243492Linux: 83. WSL / Ubuntu 22.04 - bpftool 설치
13761정성태10/11/20243210오류 유형: 927. WSL / Ubuntu - /usr/include/linux/types.h:5:10: fatal error: 'asm/types.h' file not found
13760정성태10/11/20243378Linux: 82. Ubuntu - clang 최신(stable) 버전 설치
13759정성태10/10/20244486C/C++: 177. C++ - 자유 함수(free function) 및 주소 지정 가능한 함수(addressable function) [6]
1  2  3  4  [5]  6  7  8  9  10  11  12  13  14  15  ...