When pass-by-pointer is preferred to pass-by-reference in C++?

前端 未结 13 1356
南笙
南笙 2020-12-02 18:46

I can imagine one case, in which the input parameter could be NULL so that pass-by-pointer is preferred but not pass-by-reference?

Can anybody add more cases?

相关标签:
13条回答
  • 2020-12-02 19:26

    The C++ FAQ has a very good answer for this question:

    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 should 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)
提交回复
热议问题