由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
Programming版 - 关于数组动态分配的疑问???
相关主题
回答C++的弱问题请求帮助 a C++/C question
a simple question about constructor问一个 copy constructor 的问题 (C++)
如何动态分配一个2维数组?question about c++ constructor
[合集] [求助]C程序数组的问题Is the order of initialization a, b, c or c, b, a?
c++ initialize struct在C/Fortran之间传递2维数组
c++:constructor 一问one question about initializaiton list
Test your C++ knowledge...一道 memset in C++的题
几个问题what is the difference?
相关话题的讨论汇总
话题: int话题: ppa话题: class话题: delete话题: 数组
进入Programming版参与讨论
1 (共1页)
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;

1 (共1页)
进入Programming版参与讨论
相关主题
what is the difference?c++ initialize struct
static initialization dependency c++c++:constructor 一问
How to initialize object in constructor?Test your C++ knowledge...
怎么搞的?几个问题
回答C++的弱问题请求帮助 a C++/C question
a simple question about constructor问一个 copy constructor 的问题 (C++)
如何动态分配一个2维数组?question about c++ constructor
[合集] [求助]C程序数组的问题Is the order of initialization a, b, c or c, b, a?
相关话题的讨论汇总
话题: int话题: ppa话题: class话题: delete话题: 数组