堆对象自然不支持复制语义
Heap objects don’t naturally support copy semantics
堆对象在 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单独分配内存,然后copy数据
int* c = new int(10);
int* d = new int(*c);
当你有一个有指针的 class 时,你应该确保你定义了
复制构造函数和赋值运算符,然后处理数据的副本类似于我在下面显示的方式。
例如,
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++ 中不自然支持复制语义是什么意思。我在阅读 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单独分配内存,然后copy数据
int* c = new int(10);
int* d = new int(*c);
当你有一个有指针的 class 时,你应该确保你定义了
复制构造函数和赋值运算符,然后处理数据的副本类似于我在下面显示的方式。
例如,
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;
}
};