Redian新闻
>
关于数组动态分配的疑问???
avatar
关于数组动态分配的疑问???# Programming - 葵花宝典
o*r
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
下也报错了,改起来地方太多了
avatar
T*B
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;
}
avatar
T*B
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;
}
avatar
P*x
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;

avatar
o*r
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;

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。