我有一个类在概念上执行此操作。请注意,底层数据类型在实际应用中更为复杂。这只是为了简化:
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&)
) 正在将值的拷贝分配到调用者提供的新位置。
这里有几个选项:
- 将实现分开。
- 将两个参数的版本略微更改为类似
bool getValueA2(const std::string &, const int *&)
的内容,以巩固功能。这非常丑陋,而且基本上没有吸引力。 - 照别人说的做,改签名。
- 重构这两种方法以使用实际上包含通用功能的第三种辅助方法。
如果您选择 #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/