c++ - 返回对指针的引用 - C++

标签 c++ pointers reference

考虑以下类(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/

相关文章:

performance - 如何在 Matlab 中将 "reference"转换为结构?

c++ - 有人能告诉我为什么复制这样的文件不起作用吗?

c++ - 在 C++ 中实现对象模型的库/方法

c++ - 打印出指向 char 数组第一个索引的指针的值

c - 使用多个嵌套结构指针检索内存地址

Java - 如何让类 1 和类 2 互相了解?

C++ Boost线程 sleep 死锁

c++ - 透过透明物体看不到天空盒

arrays - 在 Nim 中创建对数组的引用

C# - 获取对对象的引用数