I'm trying to use clang-tidy to enforce the C++ Core Guidelines. While it does have a lot of valid points, there is one thing I cannot really work around: dlsym returns a void*
which I need to turn into a proper function pointer somehow. To do that I use reinterpret_cast
. Since the guidelines forbid it, I have warnings about it.
Of course I can put //NOLINT
comments everywhere, but I'm looking for a solution that doesn't use reinterpret_cast
so the warnings go away.
Are there any workarounds for this problem?
There is no other way in the language to cast a function pointer type to an object pointer type except for reinterpret_cast
. Doing so is implementation-defined behavior [expr.reinterpret.cast]/8:
Converting a function pointer to an object pointer type or vice versa is conditionally-supported. The meaning of such a conversion is implementation-defined, except that if an implementation supports conversions in both directions, converting a prvalue of one type to the other type and back, possibly with different cv-qualification, shall yield the original pointer value.
That means that a conforming C++ compiler must document if it does not support this feature. And, if it does support it, it must document how exactly it behaves. You can rely on it working (or not being available) in the documented way on that compiler.
Concerning the Core Guidelines linting: If you would have to put //NOLINT
"everywhere", then that would seem to imply that you're calling naked dlsym()
in many places. Consider wrapping it, for example
template <typename T>
inline T* lookupSymbol(void* module, const char* name)
{
auto symbol = reinterpret_cast<T*>(dlsym(module, name)); // NOLINT
if (!symbol)
throw std::runtime_error("failed to find symbol '"s + name + '\'');
return symbol;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With