Why do i have to std::move an rvalue reference?

Hi
I was coding today and tried to do the following:

(constructor for my 'Socket' class, 'Socket' has a, std::unique_ptr<Platform> m_platform, member variable)
1
2
3
4
5
Socket::Socket(std::unique_ptr<Platform>&& platform) : m_platform{platform}
{

}

However, that resulted in an error. So i tried this instead:
1
2
3
4
Socket::Socket(std::unique_ptr<Platform>&& platform) : m_platform{std::move(platform)}
{

}


which worked fine.
I'm just wondering why it works when i call std::move on 'platform'?
as far as i understand std::move just turns an lvalue into an rvalue reference, but isn't the argument 'platform' already of rvalue reference type?
Last edited on
I think the reason is because you might want to use it multiple times before moving from it. If it moved automatically it could easily lead to bugs where the object is used after it has been moved from without you realising.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <memory>

void f(std::unique_ptr<int>&)  { std::cout << "lvalue ref\n"; }
void f(std::unique_ptr<int>&&) { std::cout << "rvalue ref\n"; }

int main() {
    std::unique_ptr<int> p(new int(42));
    f(p);               // lvalue ref
    f(std::move(p));    // rvalue ref
}

I understand std::move just turns an lvalue into an rvalue reference

Not quite. std::move converts lvalue expressions into rvalue expressions.

The value category of the name of a variable (platform) is lvalue. The value category of std::move(platform) is xvalue, a kind of rvalue.

P.S.: just take std::unique_ptr by value.
void f(std::unique_ptr<int> x) { consume(std::move(x)); }
Last edited on
Topic archived. No new replies allowed.