【发布时间】:2019-07-31 16:24:50
【问题描述】:
我想从函数返回布尔值或成功/失败枚举并通过引用修改参数。但是,我想在调用函数中构造一个引用,而不是复制值。
我有一些容器(比如 std::queue 类型的“example_q”)。 queue.front() 将返回对存储在队列中的值的引用。我可以复制该引用(示例 A),或者我可以获取该引用的引用(示例 B),从而允许值保留在队列中,但可以在队列之外使用。
一)
int a = example_q.front();
B)
int& b = example_q.front();
使用这种差异,我还可以返回排队的值:
一)
int get_front()
{
int a = example_q.front();
return a;
}
B)
int& get_front()
{
return example_q.front();
}
使用选项 'B' 我可以避免不必要的复制,而无需通过 std::move() 语义将数据移出队列。
我的问题是,我可以通过引用传递的参数执行“B”吗?我需要以某种方式使用 std::move()/rvalues/&& 吗?
void get_front(int& int_ref)
{
// somehow don't copy the value into referenced int_ref, but construct
// a reference in the caller based on an input argument?
int_ref = example_q.front();
}
这将解决的问题是使 API 匹配其他修改引用参数但返回成功/失败值的函数,即:
if(q.get_front(referrence_magic_here))
{
...
}
我可以颠倒顺序得到想要的结果,IE:
int& get_front(bool& success)
{
...
}
但我宁愿保留我的 API 的模式,并尽可能通过 if() 语句中的一行来完成。
可能是这样的:
bool get_front(int&& int_rvalue)
{
...
int_rvalue = example_q.front();
...
return true_or_false;
}
void calling_func()
{
...
if(get_front(int& magical_ref))
{
... //use magical_ref here?
}
...
}
【问题讨论】:
-
为什么不直接使用
int& get_front() { return example_q.front(); }?输出参数通常被认为是一个坏主意。 -
否,但您可以传递对指针的引用并修改指针以指向您的数据。更好的是,返回一个带有引用的元组以及您需要返回的任何其他内容:
std::tuple<int&, bool> get_front()。