c++将 char* 转换为对象?
在 C++ 中是否可以将字符数组转换为对象,如下所示:
char* bytes = some bytes...
MyObject obj = (MyObject)(bytes);
?
我如何定义强制转换运算符?
谢谢 :)
Is it possible in C++ to convert an array of chars to an object like so:
char* bytes = some bytes...
MyObject obj = (MyObject)(bytes);
?
How do I have to define the cast operator?
thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能想为 MyObject: 定义一个构造函数,
然后就可以使用它:
You probably want to define a constructor for MyObject:
and then you can use it:
我在这里看到两种可能性。如果您知道代表目标类型的数据,则可以使用
reinterpret_cast
将它们视为该类型的对象:如果您想在中创建指定类型的对象 指定的内存,您可以使用
placement new
运算符在指定地址构造一个对象:当您使用完该对象后,您不会
删除
它,您直接调用 dtor:请注意,要使其工作,您需要确保(如果没有其他情况)
bytes
指向与目标类型正确对齐的数据。I can see two possibilities here. If you have data that you know represents the target type, you can use a
reinterpret_cast
to get them treated as an object of that type:If you want to create an object of the specified type in the designated memory, you use the
placement new
operator to construct an object at the specified address:When you're finished using the object, you don't
delete
it, you directly invoke the dtor:Note that for this to work, you need to ensure that (if nothing else)
bytes
points to data that's aligned correctly for the destination type.如果字节串实际上表示
MyObject
类型的有效对象,则可以使用以下方法获取MyObject*
(但这不太可能起作用,除非
char*< /code> 是将指针转换为正确构造的
MyObject
的结果。)If the bytestring actually represents a valid object of type
MyObject
, you can get aMyObject*
with(This is very unlikely to work though, unless the
char*
is the result of casting a pointer to a properly constructedMyObject
.)我喜欢杰里·科芬和拉斯曼的答案,这取决于所讨论的位置是否已经有一个建筑物体。
但还有一个问题。如果
MyObject
的类型恰好符合 POD 类,那么像 larsman 建议的那样在指针上使用重新转换可能就可以了,因为该对象实际上不需要构造函数。我说“可能”是因为您的平台很可能对 char * 和类指针使用不同的表示形式。但我用过的大多数都没有这样做。
I like Jerry Coffin and larsman's answers, depending on wheather the location in question already has a constructed object in it or not.
There is one further wrinkle though. If the type of
MyObject
happens to qualify as a POD class, then it might be OK to just use a reintreprent cast on the pointer like larsman suggested, as no constructor is really required for the object.I say "might" because it is remotely possible that your platform uses different representations for
char *
and class pointers. Most I've used don't do that though.