Why is a link more secure than a pointer?

Hey i am trying to understand what is the difference between pointer and reference in safety term for use, many say that reference is safer than pointer and it cannot be null. But for the following code, it shows that a link can throw a runtime error, but not a 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 fail for the "reference part" but not for the "pointing part". My questions:

  • Why do we always say that references are safer than pointers if they might be invalid (like in the previous code) and we can't check for invalidation?

  • Is there a difference in RAM or CPU consumption between using a pointer or a reference? (Is it worth refactoring a lot of code to use a reference instead of a pointer when we can?)

+3


source to share


1 answer


Links cannot be NULL

, that is correct. However, the referenced portion of your code fails because you are explicitly trying to dereference the pointer NULL

when trying to initialize the link, not because the reference has always been NULL

:

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

      

Links can become dangling links, 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 keep 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 have a performance impact, they are probably similarly implemented under the hood depending on your compiler. Links can be fully optimized if the compiler can tell exactly what the link is attached to.

+3


source







All Articles