C++ pointers 和reference
Pointer 和 references 主要区别 reference:总代表一个对象, 没有null reference;pointer则没有限制,可以为null poiner可以被重新赋值; reference不可以被重新赋值。 应用场景 如果在不同时间指向不同对象则使用pointer, 如果一旦代表该对象就不能改变选择reference. 相关代码: 使用reference更富效率, 如下面的例子,不需要测试rd的值,他代表某一个double void printDouble(const double &rd) { cout << rd; } 而如果用pointers,那么就得测试下他是否为null。 void printDouble(const double *pd) { if (pd) { cout << *pd; } } 其他: 当然也有例外, 比如leveldb中就可以看到一下issue,DB::Get API should use reference instead of pointer #140 可以看到在下面一段描述,这里主要讨论关于函数参数使用引用还是指针。 Original issue 134 created by jvb127 on 2013-01-03T06:36:56.000Z: The current DB::Get API is defined as: virtual Status Get(const ReadOptions& options, const Slice& key, std::string* value) = 0; However, 'value' is not an optional parameter - it should point to a valid std::string. This is not checked by the implementation It could be considered to use a reference rather than a pointer: virtual Status Get(const ReadOptions& options, const Slice& key, std::string& value) = 0; 可以看到在google早些年的开发指南中,使用指针定义参数列表的参数和引用,通过const区分输入,输出参数。 ...