• placement new讲解


    【本文链接】

     http://www.cnblogs.com/hellogiser/p/placement-new.html

    【分析】

    首先我们区分下几个容易混淆的关键词:new、operator new、placement new

    new和delete操作符我们应该都用过,它们是对堆中的内存进行申请和释放,而这两个都是不能被重载的。要实现不同的内存分配行为,需要重载operator new,而不是new和delete。

    看如下代码:

    class MyClass {…};

    MyClass * p=new MyClass;

    这里的new实际上是执行如下3个过程:

    1.调用operator new分配内存;

    2.调用构造函数生成类对象;

    3.返回相应指针。

    operator new就像operator+一样,是可以重载的,但是不能在全局对原型为void operator new(size_t size)这个原型进行重载,一般只能在类中进行重载。如果类中没有重载operator new,那么调用的就是全局的::operator new来完成堆的分配。同理,operator new[]、operator delete、operator delete[]也是可以重载的,一般你重载了其中一个,那么最好把其余三个都重载一遍。

    placement new是operator new的一个重载版本,只是我们很少用到它。如果你想在已经分配的内存中创建一个对象,使用new是不行的。也就是说placement new允许你在一个已经分配好的内存中(栈或堆中)构造一个新的对象。原型中void*p实际上就是指向一个已经分配好的内存缓冲区的的首地址。

    我们知道使用new操作符分配内存需要在堆中查找足够大的剩余空间,这个操作速度是很慢的,而且有可能出现无法分配内存的异常(空间不够)。placement new就可以解决这个问题。我们构造对象都是在一个预先准备好了的内存缓冲区中进行,不需要查找内存,内存分配的时间是常数;而且不会出现在程序运行中途出现内存不足的异常。所以,placement new非常适合那些对时间要求比较高,长时间运行不希望被打断的应用程序。

    使用方法如下:

    1. 缓冲区提前分配

    可以使用堆的空间,也可以使用栈的空间,所以分配方式有如下两种:

    class MyClass {…};
    char *buf=new char[N*sizeof(MyClass)+ sizeof(int) ] ; 或者char buf[N*sizeof(MyClass)+ sizeof(int) ];

    2. 对象的构造

    MyClass * pClass=new(buf) MyClass;

    3. 对象的销毁

    一旦这个对象使用完毕,你必须显式的调用类的析构函数进行销毁对象。但此时内存空间不会被释放,以便其他的对象的构造。

    pClass->~MyClass();

    4. 内存的释放

    如果缓冲区在堆中,那么调用delete[] buf;进行内存的释放;如果在栈中,那么在其作用域内有效,跳出作用域,内存自动释放。

    注意:

    1) 在C++标准中,对于placement operator new []有如下的说明: placement operator new[] needs implementation-defined amount of additional storage to save a size of array. 所以我们必须申请比原始对象大小多出sizeof(int)个字节来存放对象的个数,或者说数组的大小。

    2) 使用方法第二步中的new才是placement new,其实是没有申请内存的,只是调用了构造函数,返回一个指向已经分配好的内存的一个指针,所以对象销毁的时候不需要调用delete释放空间,但必须调用析构函数销毁对象。

     【代码】

     C++ Code 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
     
    /*
        version: 1.0
        author: hellogiser
        blog: http://www.cnblogs.com/hellogiser
        date: 2014/9/20
    */


    #include "stdafx.h"
    #include "iostream"
    #include <new// for placement new
    using namespace std;


    class MyClass
    {
    public:
        MyClass(): m_nValue(
    0)
        {
            cout << 
    "constructor. ";
        }
        ~MyClass()
        {
            cout << 
    "destructor. ";
        }
        
    void SetValue(int value)
        {
            m_nValue = value;
        }
        
    int GetValue( )
        {
            
    return m_nValue;
        }
    private:
        
    int m_nValue;
    };


    void test_placement_new()
    {
        
    const int N = 5;
        
    // create buffer
        char *buf = new char[sizeof(MyClass)*N + sizeof(int)];
        
    // construct object at buffer
        MyClass *pc = new(buf)MyClass();
        
    // do something...
        pc->SetValue(100);
        cout << pc->GetValue() << endl;
        
    // erase object
        pc->~MyClass();

        
    // delete buffer
        delete []buf;
    }

    int main()
    {
        test_placement_new();
        
    return 0;
    }
    /*
    constructor.
    100
    destructor.
    */

    【显示调用构造函数和析构函数】

    显示调用构造函数

     C++ Code 
    1
    2
     
    MyClass *pc = (MyClass *)malloc(sizeof(MyClass));
    pc->MyClass();

     会出错,解决办法有2种:

    第一:pc->MyClass::MyClass();  显示调用构造函数需要加上MyClass::
    第二:new(pc)MyClass();  通过placement new来调用构造函数。

    placement new的作用就是:创建对象(调用该类的构造函数)但是不分配内存,而是在已有的内存块上面创建对象。用于需要反复创建并删除的对象上,可以降低分配释放内存的性能消耗。

    【构造函数】

     C++ Code 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
     
    void test_constructor()
    {
        
    //1 allocate memory
        MyClass *pc = (MyClass *)malloc(sizeof(MyClass));
        
    // 2 construct object by calling MyClass::Myclass()
        pc->MyClass::MyClass();  //  pc->MyClass(); is ERROR

        
    // 2 construct object by placement new
        //new(pc)MyClass();

        pc->SetValue(
    100);
        cout << pc->GetValue() << endl;

        
    // 3 delete object
        delete pc;
    }

    int main()
    {
        test_constructor();
        
    return 0;
    }

    /*
    constructor.
    100
    destructor.
    */


     【析构函数】

     C++ Code 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
     
    void test_destructor()
    {
        
    // 1 allocate memory and construct object
        MyClass *pc = new MyClass();

        pc->SetValue(
    100);
        cout << pc->GetValue() << endl;

        
    // 2 erase object
        pc->MyClass::~MyClass();  // pc->~MyClass();  is also OK

        
    // 3 erase object and free memory
        delete pc;
    }


    int main()
    {
        test_destructor();
        
    return 0;
    }

    /*
    constructor.
    100
    destructor.
    destructor.
    */

    【参考】

     http://blog.csdn.net/zhangxinrun/article/details/5940019

    http://www.cnblogs.com/luxiaoxun/archive/2012/08/10/2631812.html

    个人学习笔记,欢迎拍砖!---by hellogiser

    Author: hellogiser
    Warning: 本文版权归作者和博客园共有,欢迎转载,但请保留此段声明,且在文章页面明显位置给出原文连接。Thanks!
    Me: 如果觉得本文对你有帮助的话,那么【推荐】给大家吧,希望今后能够为大家带来更好的技术文章!敬请【关注】
  • 相关阅读:
    449. Serialize and Deserialize BST
    3. Longest Substring Without Repeating Characters
    2. Add Two Numbers
    240. Search a 2D Matrix II
    5. Longest Palindromic Substring
    数位DP专题(开坑。
    POJ 2356
    HDU 4055
    HDU 4054
    HDU 1559
  • 原文地址:https://www.cnblogs.com/hellogiser/p/placement-new.html
Copyright © 2020-2023  润新知