Is it OK to use C-style cast for built-in types?

后端 未结 9 837
情书的邮戳
情书的邮戳 2020-12-01 16:09

After reading here a lot of answers about C-style casting in C++ I still have one little question. Can I use C-style casting for built-in types like long x=(long)y;

9条回答
  •  时光取名叫无心
    2020-12-01 16:50

    The one case where I prefer legacy C cast is casting byte buffers to different signedness. Many APIs have different conventions, and there is no "right answer" really, and the cast is not dangerous in the context it is done, where code needs to be only as platform-agnostic as the combination of libraries being used.

    A concrete example for what I mean, I think this is just fine:

    unsigned char foo[16];
    lib1_load_foo(key);
    lib2_use_foo((char*)key);
    

    But for anything else, if cast is needed, it is going to have potential side-effects, which should stand out, and using C++ style (arguably ugly) cast is the right choice. And if cast is not needed, then don't use cast.

提交回复
热议问题