高度不是一个恒定的表达

时间:2013-06-07 00:39:41

标签: c++ c++11

如何在构造函数中为2D数组分配动态内存,但同时让我的std::unique_ptr处理它的释放?或者有更好的方法吗?

我的错误是“身高不是一个恒定的表达”。

#include <iostream>
#include <vector>
#include <memory>

template<typename T>
class Matrix
{
    private:
        int Width, Height;
        std::unique_ptr<T*> Elements;

    public:
        Matrix(int Width, int Height);

        T* operator[](int Index);
        const T* operator[](int Index) const;
};

template<typename T>
Matrix<T>::Matrix(int Width, int Height) : Width(Width), Height(Height), Elements(new T[Width][Height]) {}

template<typename T>
T* Matrix<T>::operator[](int Index) {return Elements[Index];}


int main()
{
    Matrix<int> M(4, 4);
    std::cout << M[2][2];
}

2 个答案:

答案 0 :(得分:2)

您需要使用动态数组习惯用法。分配一维向量并转换坐标。类似于:, Elements( new T[Width*Height] )。然后,您需要在运算符[]中进行数组转换,如下所示:return Elements.get()+Index*Height;

顺便提一下,您的unique_ptr应该是unique_ptr<T[]>而不是T*。如果您使用new[]进行分配,则需要unique_ptr<...[]>以确保使用delete[]进行回收。

答案 1 :(得分:1)

函数参数不能用于初始化C数组,因为它们的值在编译时不一定是已知的。像你这样进行动态分配的矩阵类也不是一个好主意...我建议将维度部分作为矩阵类模板的一部分,就像这样

template<typename T, size_t Width, size_t Height>
class Matrix
{
    private:
        std::array<std::array<T, Height>, Width> Elements;

    public:
        Matrix() {}

        std::array<T, Height> & operator[](int Index) { return Elements[Index]; }
};

所有数据都在堆栈中,因此您无需担心破坏。我在这里使用std::array但在实际代码中通常使用Vector类。

将typedef用于常用的矩阵类型

typedef Matrix<float, 2, 2> Mat2x2;
typedef Matrix<float, 3, 3> Mat3x3;
相关问题