3

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 :

  1. 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?

  2. 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 ?)

Collin
  • 11,977
  • 2
  • 46
  • 60
Aniss Be
  • 163
  • 8

1 Answers1

3

References cannot be NULL, that is correct. The reference part of your code however is crashing because you're explicitly trying to dereference a NULL pointer when you try to initialize the reference, not because the reference was ever null:

*b->getA(); // Equivalent to *((A*) NULL)

References can become dangling references though, if you did something like:

int* a = new int(5);
int& b = *a;

// Some time later
delete a;

int c = b + 2; // Ack! Dangling reference

A pointer wouldn't have saved you here, here's the equivalent code using a pointer:

int* a = new int(5);
int* b = a;

// Some time later
delete a;

if(b) { // b is still set to whatever memory a pointed to!
    int c = *b + 2; // Ack! Pointer used after delete!
}

Pointers and references are unlikely to make any performance difference, they're probably similarly implemented under the hood depending on your compiler. References might be optimized out completely if the compiler can tell exactly what the reference is bound to.

Collin
  • 11,977
  • 2
  • 46
  • 60