如果我不做const_cast <char*>并简单地使用(char*)类型转换,有什么危害吗?

Inv*_*tus 0 c++ c++11

只是想知道是否存在不使用const_cast的缺点虽然传递char*并简单地将其类型转换为(char*)或两者基本上是同一个?

  #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;
  }
Run Code Online (Sandbox Code Playgroud)

是否存在使用print((char *) (c) );过度 print( const_cast<char *> (c) ); 或基本两者相同的缺点?

Dav*_*own 8

首先,您的print函数应该采用const char*参数而不是仅仅char*因为它不修改它.这消除了对任何一个演员的需要.

至于你的问题,C++风格的转换(即const_cast,dynamic_cast等)者优先在C-风格转换,因为它们表达了投的意图,他们很容易搜索.如果我不小心使用了一个类型的变量int而不是const char*,使用const_cast将导致编译时错误.但是,如果我使用C风格的转换,它将成功编译,但在运行时会产生一些难以诊断的内存问题.


Edw*_*per 5

在这种情况下,它们是相同的(从"const char*"转换为"char*").const_cast的优点是:

  1. 它将有助于捕获拼写错误(如果你不小心将"const wchar_t*"强制转换为"char*",那么const_cast会抱怨.)
  2. 它更容易搜索.
  3. 它更容易看到.