Contents

Dynamic type violation

Detects when an object has the wrong dynamic type.

Overview

Use this check to detect when an object has the wrong dynamic type. Dynamic type violations can cause unintended code execution. Available in Xcode 9 and later.

Member call on instance with incorrect type in C++

In the following code, reinterpret_cast creates a variable with the wrong dynamic type:

struct Animal {
    virtual const char *speak() = 0;
};
struct Cat : public Animal {
    const char *speak() override {
        return "meow";
    }
};
struct Dog : public Animal {
    const char *speak() override {
      return "woof";
    }
};
auto *dog = reinterpret_cast<Dog *>(new Cat); // Error: dog has incorrect dynamic type
dog->speak(); // Error: this call has undefined behavior

The method call dog->speak() is suspect. If the speak method in Dog is final override, dog->speak() may return "woof" because the optimizer can devirtualize the call; if not, it might return "meow".

Solution

Use reinterpret_cast sparingly, and only when it’s possible to verify that the cast object is an instance of the destination type.

See Also

Undefined Behavior Sanitizer