简体   繁体   中英

Is there any harm if I don't do const_cast<char*> and simply use ( char * ) typecasting?

Just want to know if there is a disadvantage of not using const_cast While passing a char* and simply type-casting it as (char *) or both are basically one and same ?

  #include <iostream>
  #include<conio.h>
  using namespace std;

  void print(char * str)
  {
    cout << str << endl;
  }

  int main () 
  {
     const char * c = "sample text";
    //  print( const_cast<char *> (c) ); // This one is advantageous or the below one
     print((char *) (c) );               // Does the above one and this are same? 
    getch();
    return 0;
  }

Is there some disadvantage of using print((char *) (c) ); over print( const_cast<char *> (c) ); or basically both are same ?

First of all, your print function should take a const char* parameter instead of just char* since it does not modify it. This eliminates the need for either cast.

As for your question, C++ style casts (ie const_cast , dynamic_cast , etc.) are prefered over C-style casts because they express the intent of the cast and they are easy to search for. If I accidentally use an a variable of type int instead of const char* , using const_cast will result in a compile time error. However if I use a C-style cast it will compile successfully but produce some difficult to diagnose memory issues at runtime.

In this context, they are identical (casting from a "const char*" to a "char*"). The advantages of const_cast are:

  1. It will help catch typos (if you accidentally cast a "const wchar_t*" to a "char*", then const_cast will complain.)
  2. It's easier to search for.
  3. It's easier to see.

The C-style cast (char *) is equivalent if used properly . If you mess up the const_cast , the compiler will warn you, if you mess up the C-style cast you just get a bug.

const_cast is more appropriate because it only casts away constness, and otherwise will warn you about other possible mistakes (like converting one pointer type to another etc), and (char *) will just silently interpret anything you give it as char * . So if you can - better use const_cast for better type safety.

Independently on the effect that C cast do in this particular case, C cast and C++ casts are not the same: C++ distinguish between reinterpret, static, dynamic and const cast.

The semantics of these cast are different and not always equally possible.

C cast can be either static or reinterpret cast (where static is not possible). It must be used where such an ambivalence is a requirement (I cannot imagine how and when), it must be avoided where a well defined and expected behavior is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM