我了解指针和引用的语法和一般语义,但是我应该如何决定什么时候在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)将调用指针版本并在运行时中断),从可维护性的角度来看,在必须存在对象的地方使用引用是有意义的,尽管失去语法的清晰性是一种遗憾。
以下是一些指导方针。
函数使用传递的数据而不修改它:
If the data object is small, such as a built-in data type or a small structure, pass it by value.
If the data object is an array, use a pointer because that’s your only choice. Make the pointer a pointer to const.
If the data object is a good-sized structure, use a const pointer or a const
reference to increase program efficiency.You save the time and space needed to
copy a structure or a class design. Make the pointer or reference const.
If the data object is a class object, use a const reference.The semantics of class design often require using a reference, which is the main reason C++ added
this feature.Thus, the standard way to pass class object arguments is by reference.
函数修改调用函数中的数据:
1.如果数据对象是内置数据类型,则使用指针。如果你是现货代码
与fixit(&x)一样,其中x是int型,很明显这个函数打算修改x。
2.如果数据对象是一个数组,则使用唯一的选择:指针。
3.如果数据对象是结构,请使用引用或指针。
4.如果数据对象是类对象,则使用引用。
当然,这些只是指导方针,可能有不同的理由
选择。例如,cin使用基本类型的引用,因此您可以使用cin >> n
而不是cin >> &n。
从 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或“反弹”(意味着它们不能改变它们是别名的对象)这一事实之外,它真的归结为一个品味问题,所以我不会说“这更好”。
也就是说,我不同意你在文章中最后的说法,因为我不认为代码在引用中失去了清晰度。在你的例子中,
add_one(&a);
可能会更清楚
add_one(a);
因为你知道a的值很可能会改变。另一方面,函数的签名
void add_one(int* const n);
也不太清楚n是单个整数还是数组?有时您只能访问(文档记录不佳的)头文件和签名
foo(int* const a, int b);
乍一看不容易理解。
在我看来,当不需要(重新)分配或重新绑定(在前面解释的意义上)时,引用和指针一样好。此外,如果开发人员只对数组使用指针,那么函数签名就不会那么模糊。更不用说使用引用的操作符语法可读性更强了。