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

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

... 76  77  [78]  79  80  81  82  83  84  85  86  87  88  89  90  ...
NoWriterDateCnt.TitleFile(s)
11986정성태7/17/201916911오류 유형: 557. 드라이브 문자를 할당하지 않은 파티션을 탐색기에서 드라이브 문자와 함께 보여주는 문제
11985정성태7/17/201917062개발 환경 구성: 452. msbuild - csproj에 환경 변수 조건 사용 [1]
11984정성태7/9/201925589개발 환경 구성: 451. Microsoft Edge (Chromium)을 대상으로 한 Selenium WebDriver 사용법 [1]
11983정성태7/8/201914934오류 유형: 556. nodemon - 'mocha' is not recognized as an internal or external command, operable program or batch file.
11982정성태7/8/201915006오류 유형: 555. Visual Studio 빌드 오류 - result: unexpected exception occured (-1002 - 0xfffffc16)
11981정성태7/7/201918081Math: 64. C# - 3층 구조의 신경망(분류)파일 다운로드1
11980정성태7/7/201928211개발 환경 구성: 450. Visual Studio Code의 Java 확장을 이용한 간단한 프로젝트 구축파일 다운로드1
11979정성태7/7/201918488개발 환경 구성: 449. TFS에서 gitlab/github등의 git 서버로 마이그레이션하는 방법
11978정성태7/6/201917710Windows: 161. 계정 정보가 동일하지 않은 PC 간의 인증을 수행하는 방법 [1]
11977정성태7/6/201922306오류 유형: 554. git push - error: RPC failed; HTTP 413 curl 22 The requested URL returned error: 413 Request Entity Too Large
11976정성태7/4/201916682오류 유형: 553. (잘못 인증 한 후) 원격 git repo 재인증 시 "remote: HTTP Basic: Access denied" 오류 발생
11975정성태7/4/201925476개발 환경 구성: 448. Visual Studio Code에서 콘솔 응용 프로그램 개발 시 "입력"받는 방법
11974정성태7/4/201921205Linux: 22. "Visual Studio Code + Remote Development"로 윈도우 환경에서 리눅스(CentOS 7) C/C++ 개발
11973정성태7/4/201919941Linux: 21. 리눅스에서 공유 라이브러리가 로드되지 않는다면?
11972정성태7/3/201923746.NET Framework: 847. JAVA와 .NET 간의 AES 암호화 연동 [1]파일 다운로드1
11971정성태7/3/201919999개발 환경 구성: 447. Visual Studio Code에서 OpenCvSharp 개발 환경 구성
11970정성태7/2/201918594오류 유형: 552. 웹 브라우저에서 파일 다운로드 후 "Running security scan"이 끝나지 않는 문제
11969정성태7/2/201919085Math: 63. C# - 3층 구조의 신경망파일 다운로드1
11968정성태7/1/201925776오류 유형: 551. Visual Studio Code에서 Remote-SSH 연결 시 "Opening Remote..." 단계에서 진행되지 않는 문제 [1]
11967정성태7/1/201919827개발 환경 구성: 446. Synology NAS를 Windows 10에서 iSCSI로 연결하는 방법
11966정성태6/30/201918791Math: 62. 활성화 함수에 따른 뉴런의 출력을 그리드 맵으로 시각화파일 다운로드1
11965정성태6/30/201919361.NET Framework: 846. C# - 2차원 배열을 1차원 배열로 나열하는 확장 메서드파일 다운로드1
11964정성태6/30/201920922Linux: 20. C# - Linux에서의 Named Pipe를 이용한 통신
11963정성태6/29/201920651Linux: 19. C# - .NET Core Unix Domain Socket 사용 예제
11962정성태6/27/201918317Math: 61. C# - 로지스틱 회귀를 이용한 선형분리 불가능 문제의 분류파일 다운로드1
11961정성태6/27/201917842Graphics: 37. C# - PLplot - 출력 모음(Family File Output)
... 76  77  [78]  79  80  81  82  83  84  85  86  87  88  89  90  ...