Home >Backend Development >C++ >Can I Take the Address of a Standard Library Function Like `std::tolower`?
Can I Take the Address of a Function Defined in the Standard Library?
Standard C functions are powerful tools, but their interaction with syntax like std::invoke can sometimes reveal unexpected behavior. Consider the following code:
#include <cctype> #include <functional> #include <iostream> int main() { std::invoke(std::boolalpha, std::cout); // #1 using ctype_func = int(*)(int); char c = std::invoke(static_cast<ctype_func>(std::tolower), 'A'); // #2 std::cout << c << "\n"; }
The first call to std::invoke with std::boolalpha works as expected, resulting in a call to std::cout.setf(std::ios_base::boolalpha) and setting the Boolean output format. However, the second call with std::tolower raises concerns.
Is the Expected Output Guaranteed?
Unfortunately, the expected output of this code is not guaranteed in C 20. According to [namespace.std](https://en.cppreference.com/w/cpp/header/namespace/std), taking the address of a standard library function (unless it's designated as addressable) is undefined behavior. The std::tolower function falls under this category.
Why is that?
The reason lies in the fact that the C standard library header
Conclusion
In conclusion, even though std::tolower behaves similarly to a standard library function with addressable properties in the C code snippet, its underlying implementation as a C function makes taking its address undefined behavior. This behavior is not specific to std::tolower but applies to any standard library function not explicitly designated as addressable.
The above is the detailed content of Can I Take the Address of a Standard Library Function Like `std::tolower`?. For more information, please follow other related articles on the PHP Chinese website!