考虑以下类(class)。
class mapping_items
{
public:
mapping_items(){}
void add(const mapping_item* item) {
items_.push_back( item );
}
size_t count() const{
return items_.size();
}
const mapping_item& find(const std::string& pattern){
const mapping_item* item = // iterate vector and find item;
return *item;
}
private:
mapping_items(const mapping_items&); // not allowed
mapping_items& operator=(const mapping_items&); // not allowed
std::vector<const mapping_item*> items_;
};
C++ 常见问题解答说,
Use references when you can, and pointers when you have to.
那么在上面的例子中,我应该返回 const mapping_item&
还是 const mapping_item*
?
我之所以选择mapping_item&
是因为总会有一个默认的返回值可用。我永远不会有空返回。所以引用清楚地表明它不能有空值。这是正确的设计吗?
最佳答案
有一个问题 - 如果您的 find() 函数失败会怎样?如果预计这永远不会发生,那么您可以返回一个引用(如果它发生了,尽管它不应该发生,但会引发异常)。另一方面,如果它可能发生(例如在地址簿中查找姓名),则应考虑返回一个指针,因为指针可以为 NULL,表示查找失败。
关于c++ - 返回对指针的引用 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2118047/