c++ - 从将它作为参数的函数返回一个引用

标签 c++

我有一个类在概念上执行此操作。请注意,底层数据类型在实际应用中更为复杂。这只是为了简化:

class A
{
  private:
  std::map<std::string, int> database;

  public:
  bool knowsValue(std::string string_id);  // Returns true if string_id is in database
  const int& getValueA(std::string string_id);  // Returns reference to int mapped to string_id in database
}

因为为未知的 string_id 调用 getValueA 会导致错误,所以这两个命令通常一起调用:

if obj.knowsValue(string_id)
  int val = obj.getValueA(string_id)
else
  std::cout << "Value does not exist in database";

因为这需要对数据库对象进行两次后续的find操作,所以我编写了这个函数bool getValueB(std::string string_id, int& val),如果string_id在数据库中,并将映射值赋值给val

这两个getValue函数的内容几乎完全一样,所以想在getValueA中重用getValueB。通过这次尝试,这是我无法理解的地方:

const int& getValueA2(std::string string_id)
{
  static int val_tmp;  // If not static, this object is deleted after the function call and the reference becomes invalid
  if (getValueB(string_id, val_tmp))
    return static_cast<const int&>(val_tmp);
  else
    return static_cast<const int&>(0);
}

显然 static 关键字在这里是不合适的,因为该值不应该在函数之间共享。此外,在 getValueB 中引用不是 const 的事实也是次优的。

我的问题:

  • 编写 getValueA2 的正确方法是什么,它试图返回它在参数中获得的引用?中间的 val_tmp 看起来很恶心。
  • 这个结构中的引用可以是 const 吗?

我倾向于将 getValueB 更改为 const int& getValueB(std::string string_id, const bool value_exists_in_db) 来解决这个问题,但我有兴趣找到找出什么是可能的以及我哪里出错了。


编辑:请注意,const int& getValueA(std::string string_id) 的声明在理想情况下不应更改,以避免更改代码库的其余部分。

最佳答案

我认为,从根本上说,您不应该尝试将这两者结合起来,因为它们实际上在做完全不同的事情。

单参数版本 (const int& getValueA(const std::string&)) 正在返回对某处某个值的引用。

两个参数版本 (bool getValueA2(const std::string&, int&)) 正在将值的拷贝分配到调用者提供的新位置。

这里有几个选项:

  1. 将实现分开。
  2. 将两个参数的版本略微更改为类似 bool getValueA2(const std::string &, const int *&) 的内容,以巩固功能。这非常丑陋,而且基本上没有吸引力。
  3. 照别人说的做,改签名。
  4. 重构这两种方法以使用实际上包含通用功能的第三种辅助方法。

如果您选择 #4,它可能看起来像这样(请注意,我无法提供更相关的示例,因为您没有提供足够的详细信息让我这样做):

auto getValueAImpl(const std::string &key) const {
    return database.find(key);
}

const int &getValueA(const std::string &key) {
    auto it = getValueAImpl(key);
    if (it != database.end()) return it->second;
    throw std::runtime_error("key not found");
}

bool getValueA(const std::string &key, int &val) {
    auto it = getValueAImpl(key);
    if (it == database.end()) return false;
    val = it->second;
    return true;
}

关于c++ - 从将它作为参数的函数返回一个引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55756238/

相关文章:

c++ - 使用 boost::property_tree::string_path 访问值

c++ - 在方阵中,每个单元格都是黑色或白色。设计一种算法来找到最大白色子方格

c++ - QTest执行两次测试用例

c++ - 根据调用的构造函数更改成员数

c++ - 寻找 C++ 的应用程序 GUI 库

c++ - C++ istream 中的行号?

c++ - 带有 ssl 本地证书的 QNetworkRequest

c++ - 为什么在使用 unique_ptr 时没有调用析构函数?

c++ - 逻辑错误,需要协助

c++ - unordered_set.hpp 中的错误 C3083?