When to use references vs. pointers

前端 未结 17 2114
一向
一向 2020-11-22 02:27

I understand the syntax and general semantics of pointers versus references, but how should I decide when it is more-or-less appropriate to use references or pointers in an

17条回答
  •  不知归路
    2020-11-22 03:22

    There is problem with "use references wherever possible" rule and it arises if you want to keep reference for further use. To illustrate this with example, imagine you have following classes.

    class SimCard
    {
        public:
            explicit SimCard(int id):
                m_id(id)
            {
            }
    
            int getId() const
            {
                return m_id;
            }
    
        private:
            int m_id;
    };
    
    class RefPhone
    {
        public:
            explicit RefPhone(const SimCard & card):
                m_card(card)
            {
            }
    
            int getSimId()
            {
                return m_card.getId();
            }
    
        private:
            const SimCard & m_card;
    };
    

    At first it may seem to be a good idea to have parameter in RefPhone(const SimCard & card) constructor passed by a reference, because it prevents passing wrong/null pointers to the constructor. It somehow encourages allocation of variables on stack and taking benefits from RAII.

    PtrPhone nullPhone(0);  //this will not happen that easily
    SimCard * cardPtr = new SimCard(666);  //evil pointer
    delete cardPtr;  //muahaha
    PtrPhone uninitPhone(cardPtr);  //this will not happen that easily
    

    But then temporaries come to destroy your happy world.

    RefPhone tempPhone(SimCard(666));   //evil temporary
    //function referring to destroyed object
    tempPhone.getSimId();    //this can happen
    

    So if you blindly stick to references you trade off possibility of passing invalid pointers for the possibility of storing references to destroyed objects, which has basically same effect.

    edit: Note that I sticked to the rule "Use reference wherever you can, pointers wherever you must. Avoid pointers until you can't." from the most upvoted and accepted answer (other answers also suggest so). Though it should be obvious, example is not to show that references as such are bad. They can be misused however, just like pointers and they can bring their own threats to the code.


    There are following differences between pointers and references.

    1. When it comes to passing variables, pass by reference looks like pass by value, but has pointer semantics (acts like pointer).
    2. Reference can not be directly initialized to 0 (null).
    3. Reference (reference, not referenced object) can not be modified (equivalent to "* const" pointer).
    4. const reference can accept temporary parameter.
    5. Local const references prolong the lifetime of temporary objects

    Taking those into account my current rules are as follows.

    • Use references for parameters that will be used locally within a function scope.
    • Use pointers when 0 (null) is acceptable parameter value or you need to store parameter for further use. If 0 (null) is acceptable I am adding "_n" suffix to parameter, use guarded pointer (like QPointer in Qt) or just document it. You can also use smart pointers. You have to be even more careful with shared pointers than with normal pointers (otherwise you can end up with by design memory leaks and responsibility mess).

提交回复
热议问题