繁体   English   中英

使用 new 而不是 malloc 分配内存

[英]Allocating mem using new instead of malloc

我正在尝试使用new而不是malloc来计算出此代码的精确等效项。 指向浮点数组[4]指针的指针:

float (**f)[4] = (float(**)[4])malloc(2 * sizeof(float(*)[4]));
for (int p = 0; p < 2; p++) {
    f[p] = (float(*)[4])malloc(3 * sizeof(float[4]));
}

我尝试了一堆组合,但找不到正确的语法。

float (**f)[4] = new ...

您可以创建一个助手类,它可以通过转换自动为您new正确的东西。

template <unsigned N = 0> struct NewAny;

template <unsigned N> struct NewAny {
    template <typename T>
    operator T * () const { return new T[N]; }
};

template <> struct NewAny<0> {
    template <typename T>
    operator T * () const { return new T; }
};

int main () {
    float (**x)[4] = NewAny<2>();
    delete[] x;
    x = NewAny<>();
    delete x;
}

在你的例子中:

float (**f)[4] = NewAny<2>();
for (int p = 0; p < 2; p++) {
    f[p] = NewAny<3>();
}

现代 C++ 教导通过使用容器和智能指针来避免手动管理动态分配的内存的错误倾向。 您可以执行以下操作来创建Dvector

template <typename T, unsigned D> struct Vectorate;

template <unsigned N, typename T, unsigned D>
struct Vectorate<T[N], D> {
    typedef
    typename Vectorate<std::array<T, N>, D>::type type;
};

template <typename T, unsigned D>
struct Vectorate {
    typedef
    typename Vectorate<std::vector<T>, D-1>::type type;
};

template <typename T>
struct Vectorate<T, 0> {
    typedef T type;
};

在你的例子中:

Vectorate<float[4], 2>::type f;
f.resize(2);
for(auto &ff : f) ff.resize(3);

普通的旧声明(不要这样做):

try
{
    float *** f = new float ** [2];
    for (size_t i = 0; i < 2; i++)
    {
       f[i] = new float * [3];
       for (size_t j = 0; j < 3; j++)
           f[i][j] = new float[4];
    }
} catch(const std::exception & e) { /* This is a pain to deal with to avoid any leak */ }

// Now you can access via f[0][1][2]
// delete[] in reverse order.

好一点(避免使用很多分配):

try 
{
    typedef float BigArray[3][4];
    BigArray * f = new BigArray[2];
} catch(const std::exception & e) { /* here it's simple */ }
// delete with delete[] f

有点麻烦,但你不再关心内存泄漏了:

std::vector<std::vector<std::vector<float>>> f(2, std::vector<std::vector<float>>(3, std::vector<float>(4)));
// Use with f[0][1][2]

此外,正如大多数人所说,您应该将数组存储在指向浮点数的指针中,而不是指向指向浮点数的指针的指针,这会更有效率,因为您不需要在 3 个步骤中取消引用来访问元素,即:

int vectorElems = 4, columns = 3, rows = 2;
int rowStride = vectorElems * columns;  
float * f = new float[rows*columns*vectorElems];
// Access with stride:
f[0 * rowStride + 1 * vectorElems + 2] = 3.14f;

// Delete with delete[] f

还有一些模板矩阵类(例如在 opencv 中)通过提供重载 () 运算符来正确执行此操作,因此您可以访问像f(0, 1, 2)这样的对象

我不确定......但试试这个:

float **f[4];
    for(int i = 0; i < 4; i++){
        f[i] = (float**)malloc(sizeof(float**));
    }
    printf("%ld", sizeof(f));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM