数组的右值引用:它真的会发生吗?

发布于 2025-01-02 12:35:17 字数 827 浏览 0 评论 0原文

考虑一下这段代码:

#include <iostream>
using namespace std;

typedef int array[12];

array sample;

array ret1(){   //won't compile
    return sample;
}

array& ret2(){
    return sample;
}

array&& ret3(){
    return sample;  //won't compile
}

void eat(array&& v){
    cout<<"got it!"<<endl;
}

int main(){
    eat(ret1());
    eat(ret2());    //won't compile
    eat(ret3());    //compiles, but I don't really know how to write a function that returns a rvalue-reference to an array
}

实际上似乎可以编译的唯一版本是 ret3()。事实上,如果我省略实现并只是声明它,它会编译(当然永远不会链接),但实际上我不知道如何显式返回对数组的右值引用。如果这不可能发生,那么我是否可以得出这样的结论:对数组的右值引用不被禁止,但只是不能使用?

编辑:

我刚刚意识到这是可行的:

array&& ret3(){
    return std::move(sample);
}

现在的乐趣在于了解它的实际价值......

Consider this code:

#include <iostream>
using namespace std;

typedef int array[12];

array sample;

array ret1(){   //won't compile
    return sample;
}

array& ret2(){
    return sample;
}

array&& ret3(){
    return sample;  //won't compile
}

void eat(array&& v){
    cout<<"got it!"<<endl;
}

int main(){
    eat(ret1());
    eat(ret2());    //won't compile
    eat(ret3());    //compiles, but I don't really know how to write a function that returns a rvalue-reference to an array
}

The only version that actually seems to compile is ret3(). In fact, if I leave out the implementation and just declare it, it compiles (and never link of course), but really I don't know how to explicitly return a rvalue reference to an array. If this can't happen, then can I conclude that rvalue-reference to arrays aren't forbidden but just can't be used?

EDIT:

I just realized that this works:

array&& ret3(){
    return std::move(sample);
}

now the fun is understanding what it's actually worth...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦断已成空 2025-01-09 12:35:17

好吧,您现在将数组视为右值。您可以将其视为一个临时对象。您可以使用此信息,并记住修改其内容是安全的。例如,您可以编写 print_sorted(array&) 函数来打印给定数组的排序内容。为此,您可以在一些额外的缓冲区中对其进行排序,因为您不想打乱给定的数据。但是具有 print_sorted(array&&) 原型的相同函数可以就地对数组进行排序,因为它知道该对象是临时的。

然而,对没有存储动态数据的普通对象的右值引用似乎不是很有用。

Well, you are now treating your array as an r-value. You can think of it as of a temporary object. You can use this information and keep in mind it is safe to modify its contents. For example, you can write print_sorted(array&) function which will print sorted contents of given array. To do this, you can sort it in some additional buffer, since you don't want to shuffle given data. But the same function with print_sorted(array&&) prototype can sort array inplace, since it knows the object is temporary.

However, r-value references to plain objects with no dynamic data stored don't seem very useful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文