是否可以通过引用通过参数返回参考



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

我有一些容器(例如std型:: queue的'example_q'(。queue.front((将返回对队列中存储的值的引用。我可以复制该参考文献(示例A(,也可以进行该参考的参考(示例B(,允许该值留在队列中,但可以在其外部使用。

a(

int a = example_q.front();

b(

int& b = example_q.front();

使用此差异我也可以返回排队值:

a(

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))
{
    ...
}

我可以扭转订单以获得所需的结果,即:

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;

(ew!(

选项B很好。

此代码无效C :

if(get_front(int& magical_ref))

将新变量传递给函数时,您无法声明新变量。而且由于必须同时声明和初始化参考变量,因此不可能通过将其传递给函数来初始化参考。

可以,但是,这样做:

if(int &magical_ref = get_front()) {

请注意,您将检查magical_ref是否为0,这与您的示例中的状况不同。

如果您的逻辑与比较int一样简单,则可以做:

if (int& magical_ref = get_front(); magical_ref == 42)

您可以返回std::tuple<int&, /* status condition */>并检查状态。例如:

std::tuple<int&, bool> get_front() {
    static int example = 0;
    return {example, false};
}
...
// C++17's structured bindings + if statement with initializer
if (auto [ref, success] = get_front(); success) {
    ref = 42;
}

demo

最新更新