"yangyong" <ya******@xteamlinux.com.cn> wrote in message
news:bf***********@adenine.netfront.net
Simple like this:
{
int* p1 = new int( 9 );
int* p2 = p1;
delete p1;
p1 = 0;
// how to know p2 now is a wild pointer?
}
Precisely because of the problem of "wild pointers", as you call them,
having two pointers pointing to the same memory is considered bad
programming practice in most cases. As far as I know, there is no
platform-independent way of checking the validity of pointers and, even if
there was, it would be easy to forget to do so. Don't have two pointers
pointing to the same memory and you will avoid the problem.
Or :
class a1{
public:
int i;
}
void fun1( a1 * p1)
{
int i = p1->i;
delete p1;
p1 = 0;
}
void fun2( a1* p1)
{
int i = p1->i;
}
void main()
{
a1* p1 = new a1;
a1* p2 = p1;
fun1( p1 );
// how to know p2 now is a wild pointer?
fun2( p2 );
}
This is a slightly more subtle case, but the answer is similar. Having
functions that delete memory is generally regarded as bad practice
(basically, memory should be allocated in constructors and deleted in
destructors). But if you must use such functions, then you just have to
document what they do and program very carefully.
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead)