2023/9/26
深拷贝和浅拷贝
在构造对象时,会存在使用new开辟内存,这个时候如果使用默认复制构造函数,两个对象中new的数据指向同一个地址。在析构函数中使用delete释放时,释放其中一个之后再次使用另外一个程序会崩溃。所以需要构造深拷贝函数,目的在于复制的时候重新开辟新的空间
typename = object.typename; //默认的复制构造函数
/开辟新空间
typename = new int (*object.typename);
//字符串的复制
str = new char [len + 1];
strcpy(str, object.str);
同样重载赋值运算符的时候。
new和delete
注意如果析构函数中使用了delete,那么在默认构造函数必须要用new申请空间
比如
String::String(){
len = 0;
str = new char[1];
str[0] = '\0';
}
注意new和delete成对使用,new[]和delete[]成对使用
用new构造对象
首先会开辟一个新的空间,其次使用new时会调用相应的构造函数
使用定位new运算符
// placenew1.cpp -- new, placement new, no delete
#include <iostream>
#include <string>
#include <new>
using namespace std;
const int BUF = 512;
class JustTesting
{
private:
string words;
int number;
public:
JustTesting(const string &s = "Just Testing", int n = 0)
{
words = s;
number = n;
cout << words << " constructed\n";
}
~JustTesting() { cout << words << " destroyed\n"; }
void Show() const { cout << words << ", " << number << endl; }
};
int main()
{
char *buffer = new char[BUF]; // 使用new申请空间
JustTesting *pc1, *pc2;
pc1 = new (buffer) JustTesting; // 定位的new运算符
pc2 = new JustTesting("Heap1", 20); // place object on heap
cout << "Memory block addresses:\n"
<< "buffer: "
<< (void *)buffer << " heap: " << pc2 << endl;
cout << "Memory contents:\n";
cout << pc1 << ": ";
pc1->Show();
cout << pc2 << ": ";
pc2->Show();
JustTesting *pc3, *pc4;
pc3 = new (buffer) JustTesting("Bad Idea", 6);
pc4 = new JustTesting("Heap2", 10);
cout << "Memory contents:\n";
cout << pc3 << ": ";
pc3->Show();
cout << pc4 << ": ";
pc4->Show();
delete pc2; // free Heap1
delete pc4; // free Heap2
// delete pc1; 错误的,pc1实际上没有用new申请一片新的空间,只是使用了buffer的空间
delete[] buffer; // 使用delete[]释放buffer的空间,因为申请buffer空间时使用的是new[]
cout << "Done\n";
// std::cin.get();
return 0;
}