Why move from an rvalue?

88 views Asked by At

I can't understand why would we move a promise object in line

std::thread t1(Findeven,std::move(evenSum),a,b);

Effort put: I learnt about move semantics and rvlaues and lvalues, but still this part is unclear.

I was expecting data to be moved from an rvalue, not to an rvalue. I know that inside the function rvalue ref will just act as an lvalue, but still that doesn't clear the confusion. Also isn't moving risky here as that would make evenSum an rvalue, meaning it can be destroyed "pretty soon", and if it points to the data contained in shared state, the data would also be destroyed rendering it unavailable for use for FutureSum.

#include <iostream>
#include <thread>
#include <future> 
typedef long int ull;
using namespace std;

void Findeven(std::promise<ull>&& evenSumPromise,ull start, ull end) {
    ull even = 0;
    for(ull i = start ; i <= end ; i++) {
        if(i%2 == 0) {
            even++;
        }
        i++;
    }
    
    evenSumPromise.set_value(even);
}

int main() {
    ull a = 0;
    ull b = 190000;
    std::promise<ull> evenSum;
    std::future<ull> FutureSum = evenSum.get_future();
    std::thread t1(Findeven,std::move(evenSum),a,b);
    t1.join();
    cout << FutureSum.get();
}
0

There are 0 answers