Reputation: 207
I have a complex class A:
class A{
...
};
and class B is include A's pointer and has a method to return the pointer.
class B{
A* GetA(){return pA;}
A* pA;
};
Then, when I use 'GetA' to get a A's pointer, it is easier to use the illegal pointer, like:
void func(A* p){
B b;
p = b.GetA();
}
when I use 'func', I just get an illegal pointer. The code above is just a sample. And I found it is much easy to make this mistake when I am in a multi-thread environment.
Is there any method to let me sure to avoid these mistakes?
Thanks a lot
Upvotes: 0
Views: 299
Reputation: 96281
There is no general method in C++ to protect yourself from illegal pointer accesses, but there are idioms you can use to help protect yourself.
Keep your classes as representing concepts/objects and don't expose direct access to any pointers they might contain. Prefer for example descriptive methods, or for container-like classes begin
/end
style methods.
When managing pointers, prefer first to use a standard container such as vector
. They're highly tuned and debugged and will prevent many problems since they already have all the right constructors, assignment, destructor, etc.
If a standard container isn't possible prefer a smart pointer such as unique_ptr
, scoped_ptr
, shared_ptr
or weak_ptr
depending on your pointer needs. By using an appropriate smart pointer, again you make it almost impossible to unintentionally make coding mistakes.
Even using all these guidelines you can always bypass any protection you've attempted to implement. If you find yourself using a lot of casts you should step back and re-examine your design.
In your case not only would I make pA
not be accessible via accessor, I wouldn't make it a raw pointer either.
Upvotes: 2
Reputation: 9015
If you initialize the pointer in the constructor to NULL:
class B {
B() {
pA = NULL;
}
A* GetA(){return pA;}
A* pA;
}
Then you can check to see if the pointer is non-NULL before using it.
void func(A* p){
B b;
p = b.GetA();
if(p != NULL) {
//use p
}
}
Also, it seems strange that you're passing in a pointer to a function, then assigning to it without first using it. p = b.GetA();
will not change anything outside of func
. Perhaps you mean to do something like one of these?
//Caller passes reference to their pointer, caller's pointer gets set.
void func(A *&p) {
B b;
p = b.GetA();
}
//Caller passes pointer to their pointer, caller's pointer gets set.
void func(A **p){
B b;
if(p != NULL) {
*p = b.GetA();
}
}
Upvotes: 0