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
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/endstyle 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_ptrorweak_ptrdepending 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
pAnot be accessible via accessor, I wouldn’t make it a raw pointer either.