new用法总结

new可以说是个

  • 一个关键字,
  • 一个运算符
  • 可以被重载。

new operator

这个就是平时最经常用的new,用法如下程序所示:

class A
{
public:
    A(int i) :a(i){}
private:
    int a;
};

int main()
{
    A* example = new A(1);
}

说明

new operator实际上执行了以下三个步骤:

  1. 调用operator new分配内存(后面要说的第二种new),
    • 如果类本身定义了operator new,那么会调用类自己的operator new,而不是全局的;
    • 如果未定义,则是全局的
  2. 调用A的构造函数A::A(int);
  3. 返回相应的指针

operator new

operator new不调用构造函数,而仅仅分配内存,

有两个版本,

  • 前者抛出异常
  • 后者当失败时不抛出异常,而是直接返回:
void* operator new (std::size_t size);
void* operator new (std::size_t size, const std::nothrow_t& nothrow_value) noexcept;
class A
{
public:
    A(int i) :a(i){}
    void* operator new(size_t size)
    {
        cout << "call A::operator new" << endl;
        return malloc(size);
    }
    void operator delete(void* p)
    {
        cout << "call A::operator delete" << endl;
        return free(p);
    }
    void* operator new(size_t size, const nothrow_t& nothrow_value) noexcept
    {
        cout << "call A::operator new (noexcept)" << endl;
        return malloc(size);
    }
    void operator delete(void* p, const nothrow_t& nothrow_value) noexcept
    {
        cout << "call A::operator delete (noexcept)" << endl;
        free(p);
    }
private:
    int a;
};

int main()
{
    A* example1 = new A(1);
    delete example1;
    A* example2 = new(nothrow) A(2);
    delete example2;
}

placement new

placement new仅在一个已经分配好的内存指针上调用构造函数,基本形式如下:

void* operator new (std::size_t size, void* ptr) noexcept;

placement new不需要抛出异常,因为它自身不分配内存。

同时,ptr指针是已经分配好的,可能在栈上也可能在堆上,如下面的例子:

class A
{
public:
    A(int i) :a(i){}
    int getValue(){ return a; }
private:
    int a;
};

int main()
{
    A* p1 = new A(1);           //在堆上分配
    A  A2(2);                    //在栈上分配
    A* p2 = &A2;
    cout << "placement new前的值: " << p1->getValue() << "  " << p2->getValue() << endl;

    A* p3 = new(p1) A(3);       //在p1的位置上构造
    A* p4 = new(p2) A(4);       //在p2的位置上构造
    cout << "placement new后的值: " << p1->getValue() << "  " << p2->getValue() << endl;
}
//第一次输出的是1,2;在相应位置构造后,输出值变为3,4。