我可以做一个C ++对象的按位复制吗? [英] Can I make a bitwise copy of a C++ object?

查看:89
本文介绍了我可以做一个C ++对象的按位复制吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以使用逐位复制来复制C ++对象吗?我的意思是使用memcopy_s?是否有可能出错的情况?

Can C++ objects be copied using bitwise copy? I mean using memcopy_s? Is there a scenario in which that can go wrong?

推荐答案

如果它们是简单数据(POD)类型,应该工作。任何具有其他类的实例的类都可能会失败,因为您在不调用其副本构造函数的情况下复制它们。最可能的方法是它的失败是它的析构函数将释放一些内存,但是你已经复制了指向它的指针,所以你尝试从一个复制的对象中使用它,并得到一个segfault。总之,不要这样做,除非它是一个POD,你确定它将永远是一个POD。

If they're Plain Old Data (POD) types, then this should work. Any class that has instances of other classes inside it will potentially fail, since you're copying them without invoking their copy constructors. The most likely way it will fail is one of their destructors will free some memory, but you've duplicated pointers that point to it, so you then try to use it from one of your copied objects and get a segfault. In short, don't do it unless it's a POD and you're sure it will always be a POD.

这篇关于我可以做一个C ++对象的按位复制吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆