Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(). 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...

like image 425
Lorenzo Pistone Avatar asked Oct 08 '22 19:10

Lorenzo Pistone


1 Answers

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.

like image 109
Mikhail Avatar answered Oct 13 '22 11:10

Mikhail