C + +逐位复制与成员复制? [英] C++ bitwise vs memberwise copying?

查看:133
本文介绍了C + +逐位复制与成员复制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

按位复制和按成员复制有什么区别?当然,如果您复制成员,那么最终还是要复制代表成员的位?

What is the difference between bitwise and memberwise copying? Surely if you copy the members then you will end up copying the bits representing the members anyway?

推荐答案

class MyClass
{
public:
    MyClass () : m_p (new int (5)) {}
    ~MyClass () {delete m_p;}
    int* m_p;
};

MyClass a;
MyClass b;
memcpy (&a, &b, sizeof (a));

我只是通过重写它的成员变量而不首先释放它来泄漏了‘a’中的已分配整数。现在, a和 b有一个m_p指向相同的内存位置,并且两者都将在销毁时删除该地址。第二次删除该内存的尝试将崩溃。

I just leaked the allocated int in 'a' by rewriting it's member variable without freeing it first. And now 'a' and 'b' have an m_p that is pointing to the same memory location and both will delete that address on destruction. The second attempt to delete that memory will crash.

这篇关于C + +逐位复制与成员复制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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