[Qt-interest] QList<T> conversion

Alan M. Carroll amc at network-geographics.com
Tue Feb 1 18:22:44 CET 2011


Tuesday, February 1, 2011, 7:31:02 AM, you wrote:

> I've read about reinterpred_cast and I think the reason of your
> disclaimer is because the use of reinterpret_cast could be dangerous.
> What it's not clear to me is how and which cases reinterpret_cast
> could be dangerous. I suppose that in this case it's safe to use
> right?

reinterpret_cast is a very sharp knife. You can do amazing things with it, but it's very easy to cut your finger off too. It is *always* dangerous.

Basically, reinterpret_cast turns off all type safety. You, and you alone, are responsible for knowing that the compiler can treat an instance of type A as an instance of type B. To be successful, you must have a good idea of the raw memory layout of C++ data structures. Note that other types of casts will make adjustments when appropriate between types, but reinterpret_cast does not. It always compiles to no code, no instructions, it affects only the compiler's view of data.

Instances of QList<T*> being isomorphic means the memory layout doesn't depend on type T, because all pointers are the same size. Therefore you can safely change the type as long as the target types are compatible.

You can use reinterpret_cast between types of different sizes and succeed, and between types of the same size and fail (particularly if one has virtual methods and the other is plain old data).




More information about the Qt-interest-old mailing list