首页 > 解决方案 > 是否可以通过引用传递的参数返回引用?

问题描述

我想从函数返回一个布尔值或成功/失败枚举并通过引用修改参数。但是,我想在调用函数中构造一个引用,而不是复制该值。

我有一些容器(比如 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?
    }
    ...
}

标签: c++referencervalue

解决方案


不,你不能那样做。

除了在它的初始化器中,一个引用的行为就像它所引用的东西。通过将其作为函数参数传递,您可以将初始化程序“隐藏”在想要进行分配的部分中。因此,该函数无法访问事物的引用行为。

如果你想这样做,你将不得不使用指针:

void get_front(int*& int_ptr)
{
    int_ptr = &example_q.front(); 
}

int* ptr = nullptr;
get_front(ptr);

// optional:
int& ref = *ptr;

(呃!)

选项B很好。


推荐阅读