When to use references vs. pointers

前端 未结 17 2117
一向
一向 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: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).

提交回复
热议问题