Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c++ - Difference between static_cast<char*> and (char*)

this is my first question :)

I have one pile file, and I have open it like shown below ;

ifstream in ( filename,  ios :: binary | ios :: in ) 

Then, I wish hold 2 byte data in unsigned int hold ;

unsigned int hold;
in . read(static_cast<char *>(&hold), 2); 

It seems correct to me. However, when I compile it with

g++  -ansi -pedantic-errors -Werror - -Wall  -o main main.cpp 

Compiler emits error

error: invalid static_cast from type ‘unsigned int*’ to type ‘char*’ 

Actually, I have solved this problem by changing static_cast with ( char*), that is

unsigned int hold;
in . read((char*)(&hold), 2); 

My questions are :

  • What is the difference(s) between static_cast<char*> and (char*) ?
  • I am not sure whether using (char*) is a safer or not. If you have enough knowledge, can you inform me about that topic ?

NOTE : If you have better idea, please help me so that I can improve my question?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

static_cast is a safer cast than the implicit C style cast. If you try to cast an entity which is not compatible to another, then static_cast gives you an compilation time error unlike the implicit c-style cast.

static_cast gives you an error here because what you are trying to say is take an int and try to fit it in a char, which is not possible. int needs more memory than what char occupies and the conversion cannot be done in a safe manner.

If you still want to acheive this,You can use reinterpret_cast, It allows you to typecast two completely different data types, but it is not safe.
The only guarantee you get with reinterpret_cast is that if you cast the result back to the original type, you will get the same value, But no other safety guarantees.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...