CPP学习笔记(自用)

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值