[英]reinterpret_cast on a char* pointer
I had to change the prototype of a function getData()
which is basically a legacy source code. 我必须更改函数
getData()
的原型,该函数基本上是旧版源代码。 Upon changing it from returning a char*
as shown below, I started getting compile errors due to static_cast
.The question I have is , Is it safe to use reinterpret_cast
, instead of static_cast
? 如下所示,从返回
char*
更改它之后,由于static_cast
,我开始出现编译错误。我的问题是,使用reinterpret_cast
而不是static_cast
是否安全?
class C1{
public:
//void *getData() {return data;} //Legacy implementation*
char *getData() {return data;} //My new implementation
private:
char data[100];
};
int main()
{
C1 myobj;
unsigned char* begin;
begin=static_cast<unsigned char*>(myobj.getData()); *//<== This gives compile error.use reinterpret_cast ?*
return 0;
}
Is there a better solution than reinterpret_cast ? 有没有比reinterpret_cast更好的解决方案?
You can static_cast
from a void *
to any pointer type, or between pointers to related types in the sense when one herites from the other. 您可以
static_cast
从void *
到任何指针类型,或者在一个指向其他类型的指针的意义上,在指向相关类型的指针之间。
reinterpret_cast
is intended to be used between pointers to unrelated types. reinterpret_cast
旨在在指向不相关类型的指针之间使用。 Is is equivalent to a static_cast
from first type to void *
followed with a static_cast
from void *
to second type. 是相当于一个
static_cast
从第一类型至void *
随后用static_cast
从void *
到第二类型。 It T and U are unrelated types: T和U是不相关的类型:
U *u = ...;
T *t;
t = reinterpret_cast<T *>(u); /* strictly the same as would be
t = static_cast<T *>(static_cast<void *>(u)); */
It depends of what you want to accomplish. 这取决于您要完成的工作。 If you want to just use the bitwise representation of
data
, with each element interpreted as unsigned char
, then reinterpret_cast
is the way to go. 如果您只想使用
data
的按位表示形式,并且每个元素都被解释为unsigned char
,那么reinterpret_cast
是reinterpret_cast
的方法。
Your question doesn't give us enough details to figure out if it is "safe" in your case. 您的问题没有提供足够的详细信息,无法确定您的情况是否“安全”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.