문제

I have mixed feelings about static_cast, as it is the safest C++ cast available, but allows both safe and unsafe conversions at the same time, so you have to know the context to say if it is actually safe or might lead to UB (e.g. when casting to a sub-class).

So why isn't there a safer explicit cast? Here is an example, where it could be useful. In COM, they have to return the interface pointer as void** ppv, so "have to" cast explicitely

*ppv = (IInterface*) this;

which was then suggested to be replaced by a safer C++ cast

*ppv = static_cast<IInterface*>(this);

But does it make sense to make even a static_cast here? this is of a class which derives from IInterface, so one could simply write

IInterface* p = this; // implicit conversion to base, safe for sure
*ppv = p;

or use a helper like

template<class T, class U>
T implicit_cast(U p) { return p; }

*ppv = implicit_cast<IInterface*>(this);

So, is it true that static_cast is sometimes misused and can (should?) be replaced by this implicit_cast in some cases, or am I missing something?

EDIT: I know that a cast is required in COM, but it does not have to be static_cast, an implicit cast would be enough.

올바른 솔루션이 없습니다

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top