简体   繁体   English

rvalue-reference to array:它真的会发生吗?

[英]rvalue-reference to array: can it actually happen?

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() . 实际上似乎编译的唯一版本是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. 实际上,如果我省略了实现并且只是声明它,它会编译(当然也不会链接),但实际上我不知道如何显式地将rvalue引用返回给数组。 If this can't happen, then can I conclude that rvalue-reference to arrays aren't forbidden but just can't be used? 如果这不可能发生,那么我可以得出结论,对数组的rvalue-reference不是禁止的,但是不能使用吗?

EDIT: 编辑:

I just realized that this works: 我才意识到这有效:

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

now the fun is understanding what it's actually worth... 现在有趣的是了解它的实际价值......

Well, you are now treating your array as an r-value. 好吧,您现在将数组视为r值。 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. 例如,您可以编写print_sorted(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. 但是print_sorted(array&&)原型的相同函数可以对数组进行排序,因为它知道对象是临时的。

However, r-value references to plain objects with no dynamic data stored don't seem very useful. 但是,对没有存储动态数据的普通对象的r值引用似乎不太有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM