本文介绍了我可以防止对象被复制std :: memcpy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很容易使非复制类与私有副本构造和赋值运算符 boost :: noncopyable
或C ++ 11 delete
关键字:
It's easy to make noncopyable class with private copy construcor and assignment operator, boost::noncopyable
or the C++11 delete
keyword:
class MyClass {
private:
int i;
public:
MyClass(const MyClass& src) = delete;
MyClass& operator=(const MyClass& rhs) = delete;
int getI() {
return i;
}
MyClass(int _i) : i(_i){}
};
int main() {
MyClass a(1), b(2);
a = b; // COMPILATION ERROR
}
但这并不妨碍对象被深层复制一组字节:
However this doesn't prevent obiect from being deep copied as a pack of bytes:
int main() {
MyClass a(1), b(2);
std::memcpy(&a, &b, sizeof(MyClass));
std::cout << a.getI() << std::endl; // 2
}
即使尝试通过声明 operator&
private,仍然可以使用惯用语地址的实现进行复制:
Even if try to prevent it by declaring operator&
private, it's still possible to make copy using implementations of address-of idiom:
int main() {
MyClass a(1), b(2);
std::memcpy(std::addressof(a), std::addressof(b), sizeof(MyClass));
std::cout << a.getI() << std::endl; // 2
}
是否有任何方法来完全防止实例被复制字节每个字节?
Is there any method to completely prevent an instance from being copied byte per byte?
推荐答案
简单的回答是否。
这篇关于我可以防止对象被复制std :: memcpy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!