-
Crash in destructor
Hi,
Please let me know why it is crashing in destructor:
//Simulation of smart pointer
Code:
#include<iostream.h>
class smartpointer
{
public:
int *p;//ordinary pointer
public:
smartpointer(int n)
{
p =new int[n];
int *t =p;
for(int i=0;i<n;i++)
*t++=i*i;
}
int* operator++(int)
{
return p++;
}
int operator*()
{
return *p;
}
~smartpointer()
{
if(p)
delete [] p;
}
};
void main()
{
smartpointer sp(10);
for(int i=0;i<10;i++)
cout<<*sp++<<endl;
}
-
Ensure that p is initialized to 0.
The problem, it seems, is that your ++() returns p++, which is a temporary with the value of one past the address to which p refers. Thus *p++ is problematic, since the pointer p++ might not exist anymore.
-
so how can we delete the allocated memory in dTOR?
-
There are many problems with that class. Listing them from biggest to smallest problem:
- Postincrement causes the class to delete a different pointer to the one that was returned from new.
- It does not follow the rule of three.
- It mixes the concept of smart pointer AND iterator. These should be separate concepts.
- The constructor should probably be marked as explicit.
- It unnecessarily check p for NULL before deletion.
- It exposes the p member variable publicly, though this one is argueably acceptable.
-
Furthermore, the code is not indented. Indent!
Plus it uses void main. Use int main.