c+ - Courbe régulière vs. static_cast vs. dynamic_cast

Mots clés : c++pointerscastingc++

meilleur 2 Réponses c+ - Courbe régulière vs. static_cast vs. dynamic_cast

vote vote

100

void func(void *data) {   // Conversion from MyClass* -> void* is implicit   MyClass *c = static_cast<MyClass*>(data);   ... }  int main() {   MyClass c;   start_thread(&func, &c)  // func(&c) will be called       .join(); } 
if (JumpStm *j = dynamic_cast<JumpStm*>(&stm)) {   ... } else if (ExprStm *e = dynamic_cast<ExprStm*>(&stm)) {   ... } 
struct Base { }; struct Derived : Base { }; int main() {   Derived d; Base *b = &d;   dynamic_cast<Derived*>(b); // Invalid } 
vote vote

83

char c = 10;       // 1 byte int *p = (int*)&c; // 4 bytes 
*p = 5; // run-time error: stack corruption 
int *q = static_cast<int*>(&c); // compile-time error 
int *r = reinterpret_cast<int*>(&c); // forced conversion 
class MyBase  {    public:   virtual void test() {} }; class MyChild : public MyBase {};    int main() {   MyChild *child = new MyChild();   MyBase  *base = dynamic_cast<MyBase*>(child); // ok } 
MyBase  *base = new MyBase(); MyChild *child = dynamic_cast<MyChild*>(base);    if (child == 0)  std::cout << "Null pointer returned"; 
#include <exception> // …   try {    MyChild &child = dynamic_cast<MyChild&>(*base); } catch(std::bad_cast &e)  {    std::cout << e.what(); // bad dynamic_cast } 
MyBase *base = static_cast<MyBase*>(child); // ok 
// Succeeds for a MyChild object MyChild *child = dynamic_cast<MyChild*>(base); 
// Allowed, but invalid MyChild *child = static_cast<MyChild*>(base);   // Incomplete MyChild object dereferenced (*child); 
const int myConst = 5; int *nonConst = const_cast<int*>(&myConst); // removes const 
*nonConst = 10; // potential run-time error 
void print(int *p)  {    std::cout << *p; } 
print(&myConst); // error: cannot convert                   // const int* to int*   print(nonConst); // allowed 

Questions similaires