使用 new 而不是 malloc 分配 mem



我正在尝试使用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 ...

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

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]

此外,正如大多数人所说,您应该将数组存储在 pointer to float 中,而不是指针到指针到浮点数,它会更有效,因为您无需在 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)

您可以创建一个帮助程序类,该类可以通过转换自动为您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);

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

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

最新更新