dur*_*eta 1 c++ reference rvalue
我想从函数返回一个布尔值或成功/失败枚举,并通过引用修改参数。但是,我想在调用函数中构造一个引用,而不是复制该值。
我有一些容器(例如std :: queue类型的“ example_q”)。queue.front()将返回对存储在队列中的值的引用。我可以复制该引用(示例A),也可以复制该引用(示例B),从而允许该值保留在队列中,但可以在队列外使用。
一种)
int a = example_q.front();
Run Code Online (Sandbox Code Playgroud)
B)
int& b = example_q.front();
Run Code Online (Sandbox Code Playgroud)
使用此差异,我还可以返回排队的值:
一种)
int get_front()
{
int a = example_q.front();
return a;
}
Run Code Online (Sandbox Code Playgroud)
B)
int& get_front()
{
return example_q.front();
}
Run Code Online (Sandbox Code Playgroud)
使用选项“ 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();
}
Run Code Online (Sandbox Code Playgroud)
这将解决的问题是使API与其他修改引用参数但返回成功/失败值的函数匹配,即:
if(q.get_front(referrence_magic_here))
{
...
}
Run Code Online (Sandbox Code Playgroud)
我可以颠倒顺序以获得所需的结果,即IE:
int& get_front(bool& success)
{
...
}
Run Code Online (Sandbox Code Playgroud)
但是,我宁愿保留我的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?
}
...
}
Run Code Online (Sandbox Code Playgroud)
不,你不能那样做。
除了在初始化程序中,引用的行为与其引用的对象相似。通过将其作为函数参数传递,您可以从要进行分配的部分“隐藏”初始化程序。因此,该函数无法访问事物的引用行为。
如果要这样做,则必须使用指针:
void get_front(int*& int_ptr)
{
int_ptr = &example_q.front();
}
int* ptr = nullptr;
get_front(ptr);
// optional:
int& ref = *ptr;
Run Code Online (Sandbox Code Playgroud)
(E!)
选项B很好。
| 归档时间: |
|
| 查看次数: |
84 次 |
| 最近记录: |