Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Don't cast between pointer types where the source type and the target type are the same.
C++ Core Guidelines: Type.1: Avoid casts
This rule helps to remove unnecessary or suspicious casts. Obviously, when a type is converted to itself, such a conversion is ineffective. Yet the fact that the cast is used may indicate a subtle design issue or a potential for regression if types change in future. It's always safer to use as few casts as possible.
Remarks
- This rule is implemented for static casts and reinterpret casts, and checks only pointer types.
Example
dangerously generic lookup
gsl::span<server> servers_;
template<class T>
server* resolve_server(T tag) noexcept {
auto p = reinterpret_cast<server*>(tag); // C26473, also 26490 NO_REINTERPRET_CAST
return p >= &(*servers_.begin()) && p < &(*servers_.end()) ? p : nullptr;
}
void promote(server *s, int index) noexcept {
auto s0 = resolve_server(s);
auto s1 = resolve_server(index);
if (s0 && s1)
std::swap(s0, s1);
}
dangerously generic lookup - reworked
// ...
server* resolve_server(server *p) noexcept {
return p >= &(*servers_.begin()) && p < &(*servers_.end()) ? p : nullptr;
}
server* resolve_server(ptrdiff_t i) noexcept {
return !servers_.empty() && i >= 0 && i < servers_.size() ? &servers_[i] : nullptr;
}
// ...