Side note: you don't need to prefix every member var with
this->
. "this" is implied unless there's a variable with a more local scope (and such situations should be avoided anyway). It's perfectly fine to just say
numbers = new int[100];
.
Anyway... there is nothing wrong with the code as posted *unless* you are using the assignment operator or copy constructor. Consider the following scenario:
1 2 3 4
|
A a; // 'new's 100 ints
A b; // 'new's 100 ints
a = b; // crash!
| |
The reason this crashes is because it assigns
a.numbers
to
b.numbers
-- only changing the
pointer, not copying the actual buffer. Then the destructors are called for these classes, the same buffer is delete[]ed twice (which will typically cause a program crash), plus one of the buffers won't be deleted at all (memory leak).
The solution is to write your own copy constructor and assignment operator, because the defaults won't work for you in this situation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
class A
{
public:
A() // default ctor
{
numbers = new int[100];
}
A(const A& a) // copy ctor
{
numbers = new int[100];
*this = a; // I use assignment operator here for ease
}
~A()
{
delete[] numbers;
}
A& operator = (const A& a) // assignment operator
{
// copy the buffer, rather than the pointer
std::copy( a.numbers , a.numbers + 100, numbers );
return *this;
}
private:
int* numbers;
};
| |
If such a copy ctor or assignment operator is not possible / not practical / too much work / not something you want... then you can disable copying by making the copy ctor and assignment operator private:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
class A
{
public:
A();
~A();
private:
int* numbers;
// You don't even have to give these a body -- in fact it's better if you don't.
A(const A&);
A& operator = (const A&);
};
| |
This will make copying the A class illegal -- it will throw compiler errors if you attempt to do it outside the A class, or linker errors if you attempt to do it inside the A class (assuming you never give those functions a body)
EDIT:
Doh I hit "submit" just after you made that second post XD.
Anyway I'm not sure I follow what you mean in your second post. Can you post a simplistic code example?
As for determining whether or not a pointer has been deleted, no, there's no way to check. Although you can zero a pointer after it's deleted to prevent it from being deleted again... but that only works on that pointer, and not on any other pointer that point to the object.
One work around I can think of is to use a static/global pointer, and then use a pointer to a pointer. But ew. I wouldn't recommend that.