是否可以通过引用通过参数返回参考
Is it possible to return a reference via an argument passed by reference?
我想从函数返回布尔或成功/失败枚举,并通过参考修改参数。但是,我想在调用函数中构造参考,而不是复制值。
我有一些容器(例如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
- 使用作为参数返回的指针的最佳做法是什么
- 有没有办法根据 lambda 参数返回类型部分专用化我的模板化函数?
- 如何通过函数参数返回指向不规则数组的指针
- void 函数中的指针参数返回不一致的值
- 如何修复用于根据参数返回不同类型的模板类中的错误C2679?
- 是否可以通过引用通过参数返回参考
- 在C++中,如何根据类中的参数返回不同的泛型类型
- 如何根据枚举参数返回其他类型
- GoogleMock,按参数返回和正常返回,消耗数组
- 功能是否有可能使用其参数返回指针
- 推论成员函数参数 /返回类型
- C++ 基于模板参数返回类型的模板函数
- 参考参数返回副本
- 根据模板参数返回有价值的
- std::string 应该按函数的值返回还是按"std::string &s"作为参数返回?
- 将适当类型的迭代器作为参数返回适当类型的STL容器
- 根据参数返回类型
- 如何实现模板函数从模板参数返回向量
- 如何根据模板参数返回不同的类型
- 我可以从引用传递的参数返回值中声明const int吗