Hey I'm trying to understand what is the difference between pointer and reference in therm of safety to use, a lot of person say that reference are safer than pointer and it couldn't be null. But for the following code it show that reference could create run-time error but not the pointer :
class A {
public:
A(): mAi(0) {}
void ff() {std::cout << "This is A" << std::endl;}
int mAi;
};
class B {
public:
B() : mBi(0), mAp(NULL) {}
A* getA() const { return mAp; }
void ff(){std::cout << "This is B" << std::endl;}
int mBi;
A* mAp;
};
int main()
{
B* b = new B();
/// Reference part
A& rA = *b->getA();
rA.ff();
std::cout << rA.mAi << std::endl;
/// Pointer part
A* pA = b->getA();
if (NULL != pA)
{
pA->ff();
std::cout << pA->mAi << std::endl;
}
}
This code will crash for "reference part" but not for the "pointer part". My questions are :
Why we always say that reference are safer than pointers if they could be invalid (as in the previous code) and we can't check for their invalidity?
There is any difference in terms of RAM or CPU consumption between using Pointer or Reference ? (Is it worth to refactor big code to use reference instead of pointer when we can then ?)