C++ 中堆对象天然不支持复制语义的含义是什么?我在阅读 CPP FAQ https://isocpp.org/wiki/faq/csharp-java#universal-object 时发现了这一点但无法理解其含义以及对 C++ 的适用性。
最佳答案
int a = 10;
int b = a;
在上述情况下,a
的值被复制到 b
。但请考虑一下,
int* c = new int(10);
int* d = c;
在这种情况下,数据不会被复制,但两个指针都指向相同的地址。
如果删除c
,则d
指向无效内存。为了避免这种情况,
需要为d单独分配内存,然后复制数据。
int* c = new int(10);
int* d = new int(*c);
当你有一个带有指针的类时,你应该确保你定义了
复制构造函数和赋值运算符,然后处理数据的拷贝,类似于我下面展示的方式。
例如,
class A
{
private:
int* m_data;
public:
A() : m_data(NULL) { }
A(int x) : m_data(new int(x)) { }
~A() { delete m_data; }
// Failing to provide the below 2 functions will
// result in shallow copy of pointers
// and results in double delete of pointers.
A(const A& other) : m_data(new int(*(other.m_data)) { }
A& operator=(const A& other)
{
A temp (other);
std::swap (m_data, temp.m_data);
return *this;
}
};
关于c++ - 堆对象天然不支持复制语义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29117932/