o******r 发帖数: 259 | 1 问题出在释放数组空间的时候
有一个class A;
申请内存
A *pA = new A[10];
释放时
delete[] pA;
debug version就会报错
release version没有报错
改成指针
A *ppA = new A*[10];
for (int i = 0; i<10; i++) ppA[i] = new A;
释放时
for (i = 0; i<10; i++) delete ppA[i];
delete[] ppA;
就没错
有谁知道两者区别?跟数组分配有关吗?
用后面那种方式写的时候比较罗嗦,用前面这种方式写的在程序负责以后在release version
下也报错了,改起来地方太多了 |
T***B 发帖数: 137 | 2 But if class A doesn't provide a default constructor, there might
be a problem to initialize an object array using this syntx. For example
class A {
int i;
public:
A(int v) {
i = v;
}
};
int main() {
A* ptr = new A(5) [10]; // wrong here
delete [] ptr;
} |
T***B 发帖数: 137 | 3 I don't think so. The following code will fail the compilation.
class A {
int i;
public:
A(int v) {
i = v;
}
};
int main() {
A a;
} |
P*****x 发帖数: 72 | 4 you are right. //blush. compiler only generates default one when no constructor
was declared.
【在 T***B 的大作中提到】 : I don't think so. The following code will fail the compilation. : class A { : int i; : public: : A(int v) { : i = v; : } : }; : int main() { : A a;
|
o******r 发帖数: 259 | 5 My original code is a little bit long.
Without changing the class body, how could the error message disappear
when I just replace the object array with pointer array instead.
At first I doubt something goes wrong with the class definition.
However I met this problem for nearly all the classes I used.
So I changed my code for pointer arrays afterwards though don't know why.
【在 T***B 的大作中提到】 : I don't think so. The following code will fail the compilation. : class A { : int i; : public: : A(int v) { : i = v; : } : }; : int main() { : A a;
|