右值引用

阅读量: searchstar 2022-10-04 22:19:01
Categories: Tags:

带名字的右值引用使用的时候会变成左值引用

result type must be constructible from input type

#include <iostream>
#include <vector>
#include <memory>

struct X {
X(int i) : i_(i){}
X() = delete;
X(const X&) = delete;
X(X&&) = default;
int i_;
};

struct A {
A(std::vector<std::unique_ptr<X>>&& x) : x_(x) {}
std::vector<std::unique_ptr<X>> x_;
};

int main() {
return 0;
}

编译错误:result type must be constructible from input type

这是因为A(std::vector<std::unique_ptr<X>>&& x) : x_(x) {}里面,x_(x)中的x是有名字的,所以它被使用的时候类型会变成左值引用。所以解决方案就是用std::move(x)强行将其又变成右值引用:

#include <iostream>
#include <vector>
#include <memory>

struct X {
X(int i) : i_(i){}
X() = delete;
X(const X&) = delete;
X(X&&) = default;
int i_;
};

struct A {
- A(std::vector<std::unique_ptr<X>>&& x) : x_(x) {}
+ A(std::vector<std::unique_ptr<X>>&& x) : x_(std::move(x)) {}
std::vector<std::unique_ptr<X>> x_;
};

int main() {
return 0;
}

cannot bind rvalue reference of type ‘int&&’ to lvalue of type ‘int’

#include <iostream>

void ss(int&& a){
std::cout << a << std::endl;
}
int main(){
int a = 1;
int&& b = std::move(a);
ss(b);
return 0;
}

int&& b是带名字的,所以在ss(b)里,使用b的时候会变成左值引用。解决方案就是再加一个std::move(b)

#include <iostream>

void ss(int&& a){
std::cout << a << std::endl;
}
int main(){
int a = 1;
int&& b = std::move(a);
- ss(b);
+ ss(std::move(b));
return 0;
}