When to use references vs. pointers

前端 未结 17 2100
一向
一向 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:06

    References are cleaner and easier to use, and they do a better job of hiding information. References cannot be reassigned, however. If you need to point first to one object and then to another, you must use a pointer. References cannot be null, so if any chance exists that the object in question might be null, you must not use a reference. You must use a pointer. If you want to handle object manipulation on your own i.e if you want to allocate memory space for an object on the Heap rather on the Stack you must use Pointer

    int *pInt = new int; // allocates *pInt on the Heap
    
    0 讨论(0)
  • 2020-11-22 03:08

    Any performance difference would be so small that it wouldn't justify using the approach that's less clear.

    First, one case that wasn't mentioned where references are generally superior is const references. For non-simple types, passing a const reference avoids creating a temporary and doesn't cause the confusion you're concerned about (because the value isn't modified). Here, forcing a person to pass a pointer causes the very confusion you're worried about, as seeing the address taken and passed to a function might make you think the value changed.

    In any event, I basically agree with you. I don't like functions taking references to modify their value when it's not very obvious that this is what the function is doing. I too prefer to use pointers in that case.

    When you need to return a value in a complex type, I tend to prefer references. For example:

    bool GetFooArray(array &foo); // my preference
    bool GetFooArray(array *foo); // alternative
    

    Here, the function name makes it clear that you're getting information back in an array. So there's no confusion.

    The main advantages of references are that they always contain a valid value, are cleaner than pointers, and support polymorphism without needing any extra syntax. If none of these advantages apply, there is no reason to prefer a reference over a pointer.

    0 讨论(0)
  • 2020-11-22 03:09

    Like others already answered: Always use references, unless the variable being NULL/nullptr is really a valid state.

    John Carmack's viewpoint on the subject is similar:

    NULL pointers are the biggest problem in C/C++, at least in our code. The dual use of a single value as both a flag and an address causes an incredible number of fatal issues. C++ references should be favored over pointers whenever possible; while a reference is “really” just a pointer, it has the implicit contract of being not-NULL. Perform NULL checks when pointers are turned into references, then you can ignore the issue thereafter.

    http://www.altdevblogaday.com/2011/12/24/static-code-analysis/

    Edit 2012-03-13

    User Bret Kuhns rightly remarks:

    The C++11 standard has been finalized. I think it's time in this thread to mention that most code should do perfectly fine with a combination of references, shared_ptr, and unique_ptr.

    True enough, but the question still remains, even when replacing raw pointers with smart pointers.

    For example, both std::unique_ptr and std::shared_ptr can be constructed as "empty" pointers through their default constructor:

    • http://en.cppreference.com/w/cpp/memory/unique_ptr/unique_ptr
    • http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr

    ... meaning that using them without verifying they are not empty risks a crash, which is exactly what J. Carmack's discussion is all about.

    And then, we have the amusing problem of "how do we pass a smart pointer as a function parameter?"

    Jon's answer for the question C++ - passing references to boost::shared_ptr, and the following comments show that even then, passing a smart pointer by copy or by reference is not as clear cut as one would like (I favor myself the "by-reference" by default, but I could be wrong).

    0 讨论(0)
  • 2020-11-22 03:10

    The performances are exactly the same, as references are implemented internally as pointers. Thus you do not need to worry about that.

    There is no generally accepted convention regarding when to use references and pointers. In a few cases you have to return or accept references (copy constructor, for instance), but other than that you are free to do as you wish. A rather common convention I've encountered is to use references when the parameter must refer an existing object and pointers when a NULL value is ok.

    Some coding convention (like Google's) prescribe that one should always use pointers, or const references, because references have a bit of unclear-syntax: they have reference behaviour but value syntax.

    0 讨论(0)
  • 2020-11-22 03:10

    Points to keep in mind:

    1. Pointers can be NULL, references cannot be NULL.

    2. References are easier to use, const can be used for a reference when we don't want to change value and just need a reference in a function.

    3. Pointer used with a * while references used with a &.

    4. Use pointers when pointer arithmetic operation are required.

    5. You can have pointers to a void type int a=5; void *p = &a; but cannot have a reference to a void type.

    Pointer Vs Reference

    void fun(int *a)
    {
        cout<<a<<'\n'; // address of a = 0x7fff79f83eac
        cout<<*a<<'\n'; // value at a = 5
        cout<<a+1<<'\n'; // address of a increment by 4 bytes(int) = 0x7fff79f83eb0
        cout<<*(a+1)<<'\n'; // value here is by default = 0
    }
    void fun(int &a)
    {
        cout<<a<<'\n'; // reference of original a passed a = 5
    }
    int a=5;
    fun(&a);
    fun(a);
    

    Verdict when to use what

    Pointer: For array, linklist, tree implementations and pointer arithmetic.

    Reference: In function parameters and return types.

    0 讨论(0)
  • 2020-11-22 03:17

    From C++ FAQ Lite -

    Use references when you can, and pointers when you have to.

    References are usually preferred over pointers whenever you don't need "reseating". This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside.

    The exception to the above is where a function's parameter or return value needs a "sentinel" reference — a reference that does not refer to an object. This is usually best done by returning/taking a pointer, and giving the NULL pointer this special significance (references must always alias objects, not a dereferenced NULL pointer).

    Note: Old line C programmers sometimes don't like references since they provide reference semantics that isn't explicit in the caller's code. After some C++ experience, however, one quickly realizes this is a form of information hiding, which is an asset rather than a liability. E.g., programmers should write code in the language of the problem rather than the language of the machine.

    0 讨论(0)
提交回复
热议问题