破解const数组大小限制

时间:2015-02-22 12:28:19

标签: c++ arrays

c ++标准不支持vsa(可变大小数组),但仅适用于多维数组。初始化像这样的onedimensional数组就像一个魅力:

uint32_t width = 640; // some non-constant value
Object arrayOfObjects = new Object[width];

从技术上讲,可以编写一个包装器对象来绕过这个限制,如下所示:

class 2DarrayWrapper{
public:
    2DarrayWrapper(uint32_t width, uint32_t height):theArray(new Object[width * height]), width(width), height(height) {};
    Object* theArray;
    uint32_t width;
    uint32_t height;

    inline Object* operator[](int index) {
        return &theArray[width*index];
    };
};

uint32_t width = 640;
uint32_t height = 400;

2DarrayWrapper wrapper = new 2DarrayWrapper(width, height);
wrapper[25][30] = 35;
delete wrapper;

我想知道的是,这种方法的一般缺点是什么?没有给出常数,所以我可以想象速度会降低,因为此时编译器无法优化内存访问。

另外,你可以模仿这种设计,使其更具动感......

0 个答案:

没有答案