[code posted below for brevity]
i want to know the deifferent betweent aaa m1[100] and aaa *p = new [100]
aaa m1[100] will call aaa() 100 times and ~aaa() 100 times
but aaa *p = new [100] will call aaa() 100 times and dont call ~aaa()
why??
There are a couple differences between declaring an array and a pointer
to an array.
The one that most concerns your code is that declaring an array (e.g.
aaa m1[100]
makes what's called an automatic variable. When main is
called, space is automagically allocated for m1 and the constructor is
called for each element. When the main function returns, the destructor
is automatically called for each element and the space m1 takes up is
deallocated. Thus you get the 100 messages about the elements in m1
being deallocated.
The same is true for the *pointer* p. When main is called, space for p
is allocated, and when main exits the space is deallocated. (p doesn't
have a constructor or destructor... keep reading.) The problem comes
with the fact that p and what p points to -- the array of aaas -- are
not the same. C++ doesn't care that, when main returns, what p pointed
to is no longer reachable; it just carries right on. Thus the
destructor is never called, and the space the array takes up isn't
deallocated. You have what is called a memory leak, because your
program has memory that is useless (the technical term is garbage) but
that it can't deallocate because it doesn't know it's useless. So it's
wasting it.
You need to add a 'delete[] p;' line before you return from main. This
will call the destructor for each element in the array p points to, and
deallocate the space.
That's not the only differece though. While pointers and arrays are
mostly interchangable, they aren't completely. One difference is what
sizeof() says; sizeof(p) will probably return 4 (depending on the
platform and compiler you are running), while sizeof(m1) might return
400, and will at least return something a couple orders of magnitude
larger than sizeof(p). This is because sizeof(p) knows that p is a
pointer, but knows nothing about what it points to, while m1 is an
array of 100 aaas. Each aaa takes up, say, 4 bytes (since is has
exactly one field, an int, and no virtual functions), so 100 of them
take up 400 bytes. (Your numbers may vary significantly. I didn't even
bother to check if these are what comes out on my system. Take them
with a grain of salt, and try it out yourself to see what they are.
Just add cout << sizeof(stuff); in there, with 'stuff' replaced by aaa,
m1, or p.)
newbie
code
--------------------------
#include <iostream>
using namespace std;
#include <cstring>
class aaa
{
private:
int age;
static int num ;
public:
aaa();
~aaa();
};
aaa::aaa()
{
++num;
cout << " call aaa() one time number =:" << num << endl;
}
aaa::~aaa()
{
--num;
cout << " call ~aaa()one time number =:" << num << endl;
}
int aaa::num =0;
int main()
{
aaa m1[100];
aaa *p = new aaa[100];
;
return 0;
}
----------------------------------