c++ new(不断跟新)

1.基础知识

/*
可以定义大小是0的数组,但不能引用,因为没有指向任何对象
new string[10]调用类的默认构造函数
new int[10]没有初始化,但new int[10]()会将数组初始化成0,返回第一个元素的首地址
*/
#include <iostream>
#include <string>
using namespace std;
int main()
{
#if 0
    //int* psa = new int[10](89);//不能这样初始化
    int* psa = new int[10]();//只能初始化成0
    for (int i = 0; i < 10; ++i)
    {
        cout<<psa[i];
    }
#endif
    /*
    类类型总是会调用默认构造函数进行初始化,不管有没有显示的初始化
    内置类型或者没有定义默认构造函数的类则不同
    new失败抛出bad_alloc异常
    delete pi;//删除一个对象
    delete []pi;//删除一个数组
    内存泄露:听着挺霸气的,其实就是删除分配的内存失败
    */
#if 1
    const int* pci = new const int(1024);//const必须初始化,对于没有提供默认的类或者内置的类型则失败,动态分配const用处不大
    string* ps = new string("2345");
    int* pi = new int;
    int* pi2 = new int(200);
#endif
    system("pause");
}

2.placement new 

#include <iostream>
using namespace std;

struct MyStruct
{
    int s;
};
int main()
{
    void* addr = new MyStruct;//缓冲区地址,大小为mysturct的大小
    //在缓冲区上分配内存,调用placement new,placement new重载operator new
    //这句相当于把addr看成int类型的指针,然后调用要调用对象的构造函数,返回值还是addr的值
    //其实就是在缓冲区上分配一块内存,然后返回这块缓冲的指针
    int * naddr = new (addr)int;
    *naddr = 90;
    cout << *naddr;
    getchar();
}     

 3.容易忘记delete

class MyClass
{
public:
    void init()
    {
        ptr = new int;
    }

public:
    int* ptr;
};
#include <iostream>
#include <vld.h>
#include <windows.h>
int main()
{
    while (true)
    {
        MyClass* ptr = new MyClass;
        ptr->init();
        delete ptr->ptr;
        delete ptr;
        Sleep(500);
    }
    getchar();
    return 0;
}

需要把成员函数中new的delete掉,不然会内存泄露

原文地址:https://www.cnblogs.com/zzyoucan/p/3733214.html