我了解指针和引用的语法和一般语义,但是我应该如何决定什么时候在API中使用引用或指针比较合适?

当然,有些情况需要其中一个(操作符++需要引用参数),但一般来说,我发现我更喜欢使用指针(和const指针),因为语法很清楚,变量是破坏性传递的。

例如,在以下代码中:

void add_one(int& n) { n += 1; }
void add_one(int* const n) { *n += 1; }
int main() {
  int a = 0;
  add_one(a); // Not clear that a may be modified
  add_one(&a); // 'a' is clearly being passed destructively
}

使用指针,它总是(更)明显的发生了什么,所以对于api和类似的地方,清晰度是一个大问题,指针不是比引用更合适吗?这是否意味着引用应该只在必要时使用(例如操作符++)?其中一种是否存在性能问题?

编辑(过时的):

除了允许NULL值和处理原始数组之外,选择似乎还取决于个人喜好。我接受下面的答案,引用谷歌的c++风格指南,因为他们提出的观点是“引用可能会令人困惑,因为它们有值语法,但有指针语义。”

由于需要额外的工作来清除不应该为NULL的指针参数(例如,add_one(0)将调用指针版本并在运行时中断),从可维护性的角度来看,在必须存在对象的地方使用引用是有意义的,尽管失去语法的清晰性是一种遗憾。


当前回答

两者的性能完全相同,因为引用是作为指针在内部实现的。因此你不需要担心这个。

关于何时使用引用和指针,没有普遍接受的约定。在少数情况下,您必须返回或接受引用(例如,复制构造函数),但除此之外,您可以自由地按照自己的意愿进行操作。我遇到的一个相当常见的约定是,当形参必须引用现有对象时使用引用,当可以使用NULL值时使用指针。

一些编码约定(如谷歌的)规定应该总是使用指针或const引用,因为引用有一点不清楚的语法:它们有引用行为但有值语法。

其他回答

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

从 C++ 常见问题精简版 -

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.

就像其他人已经回答的那样:总是使用引用,除非变量为NULL/nullptr是一个真正有效的状态。

约翰·卡马克在这个问题上的观点也类似:

空指针是C/ c++中最大的问题,至少在我们的代码中是这样。将一个值同时用作标志和地址会导致大量致命问题。在任何可能的情况下,c++引用应该比指针更受欢迎;虽然引用“实际上”只是一个指针,但它有一个非null的隐含契约。当指针转换为引用时执行NULL检查,然后可以忽略此问题。

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

编辑2012-03-13

用户Bret Kuhns正确地评论道:

c++ 11标准已经完成。我认为是时候在这个线程中提到,大多数代码应该可以很好地使用引用、shared_ptr和unique_ptr的组合。

确实如此,但是问题仍然存在,即使用智能指针替换原始指针也是如此。

例如,std::unique_ptr和std::shared_ptr都可以通过它们的默认构造函数构造为“空”指针:

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

... 这意味着在不验证它们是否为空的情况下使用它们会有崩溃的风险,这正是J. Carmack讨论的全部内容。

然后,我们有一个有趣的问题:“如何将智能指针作为函数参数传递?”

Jon对这个问题的回答是c++——将引用传递给boost::shared_ptr,下面的注释表明,即使这样,通过复制或引用传递智能指针也不像人们想的那样明确(默认情况下我倾向于使用“通过引用”,但我可能错了)。

我的经验法则是:

Use pointers for outgoing or in/out parameters. So it can be seen that the value is going to be changed. (You must use &) Use pointers if NULL parameter is acceptable value. (Make sure it's const if it's an incoming parameter) Use references for incoming parameter if it cannot be NULL and is not a primitive type (const T&). Use pointers or smart pointers when returning a newly created object. Use pointers or smart pointers as struct or class members instead of references. Use references for aliasing (eg. int &current = someArray[i])

无论您使用哪一种,如果参数不明显,请不要忘记记录函数及其参数的含义。

两者的性能完全相同,因为引用是作为指针在内部实现的。因此你不需要担心这个。

关于何时使用引用和指针,没有普遍接受的约定。在少数情况下,您必须返回或接受引用(例如,复制构造函数),但除此之外,您可以自由地按照自己的意愿进行操作。我遇到的一个相当常见的约定是,当形参必须引用现有对象时使用引用,当可以使用NULL值时使用指针。

一些编码约定(如谷歌的)规定应该总是使用指针或const引用,因为引用有一点不清楚的语法:它们有引用行为但有值语法。