1

I've got a rather simple, though large, system setup. It stores it's data in a void* array because the data it's storing could vary between float or double depending on how much accuracy is needed.

just doing delete [] data raises a warning: deleting 'void*' is undefined [enabled by default] using MinGW. And I've got another variable to tell me if data is a float* or a double*, but does it matter which I use?

In other words, could I use the fallowing code without worrying about memory-leak's, or other errors/damage not caught by the compiler?

double* d_data = new double[length];
data = (void*)d_data;
delete [] (float*)data;
4

3 回答 3

3

这当然很重要;您使用的指针delete[]必须与您分配的指针具有相同的类型。所以强制转换double*为有效(但容易出错);强制转换为float*给出未定义的行为。

[对于类类型的单个对象(不是数组)有一个例外 -如果该基类具有虚拟析构函数,它可以是指向基类的指针。但这不适用于原始类型,如double, 或数组。]

至于内存泄漏:手动内存管理总是存在内存泄漏的危险,除非您非常小心,不要做任何可能引发异常的事情。我强烈推荐使用RAII来管理所有动态资源。

于 2013-03-06T23:52:21.347 回答
1

看来您可能想使用union

于 2013-03-06T23:46:56.010 回答
0

是的,这很重要(并且转换为其他数据类型本质上与 leave 一样糟糕void*),因为您本质上是在丢失/搞砸额外的元数据(如实际长度)。它可能不一定会崩溃(例如,您可以使用delete data;而不是delete [] data;也可以,除非编译器注意到错误,否则它会泄漏),因为它本质上是未定义的行为(不同的编译器或版本可能会产生不同的结果)。

正如 Jorge 建议的那样,您可能只想为此使用联合,因此两种数据类型可以共享相同的内存:

union my_union {
    double d_double;
    float d_float;
};

根据编译器的不同,这个结构通常与内部最大的数据类型大小相同(在这种情况下(在 32 位机器上)可能是 8 个字节的双精度,4 个字节的浮点数;所以总大小为 8字节,因为这些变量本质上是重叠的)。请记住,您不能将其用于某种自动转换。

于 2013-03-06T23:55:26.140 回答