如何在C++中动态分配二维数组-续 - 李凡希的Blog

何在C++中动态分配二维数组-续

  回头看一下前一篇《如何在C++中动态分配二维数组》才发现它是挂羊头卖狗肉,文中只提了从ChinaUnix上拿来的那个C的实现,还是没有结论说对于C++的对象应该怎么处理。今天抽空写了一下。

  关键点还是在于placement new和显示的析构函数调用,用于保证对象可以正常的构造和析构。

  不过这个实现也还是有不少缺点的,比如,数组的大小必须记住,才能保证析构所有对象。不过这点可以通过改进分配方法算法,把数组大小也用一点空间保存起来。

  另一个缺点是,从语法上看,很容易让人误把darray_new返回的指针以为是数据区的起始地址,从而可能导致一些逻辑错误。

  其实正像ftofficer在前一篇文章的留言中说的那样,最好的办法还是不要“造轮子”了,有强大的Boost放在那里不用实在是太浪费了……

#include <iostream>
#include <cstdlib>
#include <new>

template <typename T>
T **darray_new(int row, int col)
{
    int size = sizeof(T);
    void **arr = (void **) malloc(sizeof(void *) * row + size * row * col);
    if (arr != NULL)
    {
        unsigned char * head;
        head = (unsigned char *) arr + sizeof(void *) * row;
        for (int i = 0; i < row; ++i)
        {
            arr[i] =  head + size * i * col;
            for (int j = 0; j < col; ++j)
                new (head + size * (i * col + j)) T;
        }
    }
    return (T**) arr;
}

template <typename T>
void darray_free(T **arr, int row, int col)
{
    for (int i = 0; i < row; ++i)
        for (int j = 0; j < col; ++j)
            arr[i][j].~T();
    if (arr != NULL)
        free((void **)arr);
}

Introduction

Face   李凡希,江苏吴江人。热爱计算机,勤于探索,愿意与您交流心得。

Miniblog

Subscribe RSS Feed


订阅到抓虾
Add to Google

Contact

Email: Email
Messenger: Live Messenger
GTalk: Google Talk
HAM Radio:BG4XTR

Visitors

Locations of visitors to this page

Links

Archive