c++ - 是否可以通过引用传递的参数返回引用?
问题描述
我想从函数返回一个布尔值或成功/失败枚举并通过引用修改参数。但是,我想在调用函数中构造一个引用,而不是复制该值。
我有一些容器(比如 std::queue 类型的“example_q”)。queue.front() 将返回对存储在队列中的值的引用。我可以制作该引用的副本(示例 A),或者我可以获取该引用的引用(示例 B),从而允许该值保留在队列中,但可以在队列之外使用。
一种)
int a = example_q.front();
二)
int& b = example_q.front();
使用这种差异,我还可以返回排队的值:
一种)
int get_front()
{
int a = example_q.front();
return a;
}
二)
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))
{
...
}
我可以颠倒顺序以获得所需的结果,即:
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?
}
...
}
解决方案
不,你不能那样做。
除了在它的初始化器中,一个引用的行为就像它所引用的东西。通过将其作为函数参数传递,您可以将初始化程序“隐藏”在想要进行分配的部分中。因此,该函数无法访问事物的引用行为。
如果你想这样做,你将不得不使用指针:
void get_front(int*& int_ptr)
{
int_ptr = &example_q.front();
}
int* ptr = nullptr;
get_front(ptr);
// optional:
int& ref = *ptr;
(呃!)
选项B很好。
推荐阅读
- rust - 如何从哈希图中删除多个元素?
- vue.js - webpack vue cli 重新加载时清除浏览器控制台
- string - 在 Perl 中将 strnig 作为计算器程序的输入
- c# - 如何为函数 MAPISendMail 指定编组
- r - 随机化 R 中的两组数字,而不是在组之间重复值
- python - 如果在至少一个列中不包含小于 0.05 的值,则从 Pandas 数据框中删除行
- animation - 如何使用 ffmpeg 指定输出图像帧的确切数量?
- material-ui - 如何在 Storybook 5 中摇树 Lodash 和 Mui 导入
- amazon-web-services - 如何从云跟踪删除策略中检查?
- asynchronous - 如何在 CompletableFuture 中激活 RequestScope(获取 org.jboss.weld.context.ContextNotActiveException)