c++ 疑难杂症(2) std::move
c++中, 动不动就看到std::move, 是为啥呢,必须地深入学习一下。
0、定义与解释
std::move 是 C++11 标准库中的一个函数,用于将一个左值表达式转换为右值引用。它使得资源可以从一个对象转移到另一个对象,这在实现移动语义和移动构造函数时非常有用。
移动语义 在 C++ 中,资源管理通常是通过拷贝构造函数和拷贝赋值运算符来实现的。但在某些情况下,我们可能希望以更高效的方式转移资源,而不是复制它们。这就是移动语义的用武之地。
std::move 的用途
- 转换左值到右值:std::move 函数可以将左值表达式转换为右值引用。这在编写接受右值引用的函数或实现移动构造函数时非常有用。
- 强制类型转换:在某些情况下,你可能需要强制将一个左值转换为右值引用,即使编译器可能不会自动进行这种转换。
- 优化性能:通过移动语义,可以避免不必要的拷贝操作,从而提高性能。
1、std::move实现
template
struct remove_reference {
using type = _Ty;
using _Const_thru_ref_type = const _Ty;
};
template
struct remove_reference<_ty&> {
using type = _Ty;
using _Const_thru_ref_type = const _Ty&;
};
template
struct remove_reference<_ty&&> {
using type = _Ty;
using _Const_thru_ref_type = const _Ty&&;
};
template
using remove_reference_t = typename remove_reference<_ty>::type;
template
[[nodiscard]] constexpr remove_reference_t<_ty>&& move(_Ty&& _Arg) noexcept {
return static_cast<remove_reference_t<_ty>&&>(_Arg);
}
小言解析如下:
这段代码是C++的模板元编程,它定义了一个模板结构remove_reference,该结构用于移除类型_Ty的引用修饰符。C++的类型系统允许对类型进行引用,如int&或int&&,但有时我们需要一个没有引用的版本,这就是这段代码的目的。
具体来说,remove_reference模板有以下几种特化:
- 对于非引用类型(_Ty),它直接返回_Ty。
- 对于左值引用类型(_Ty&),它返回一个没有引用的类型_Ty。
- 对于右值引用类型(_Ty&&),它返回一个没有引用的右值引用类型const _Ty&&。
然后,定义了一个别名模板remove_reference_t,它使用了typename remove_reference<_ty>::type来获得移除引用后的类型。
最后,定义了一个函数模板move,它接受一个右值引用参数,并返回一个移除引用后的右值引用。这是为了在某些上下文中提供移动语义,例如在完美转发的情况下。
总的来说,这段代码的目的是为了在编译时处理类型,移除其可能存在的引用修饰符,以便在需要原始类型而没有引用的情况下使用。
2、示例
#include
#include
#include
void main() {
//remove_reference的调用
int x = 0;
int& ref_x = x;
int&& ref_xx = static_cast(x);
int&& y = std::move(x); //remove_reference
int&& y2 = std::move(ref_x);//remove_reference<_ty&>
int&& y3 = std::move(ref_xx);//remove_reference<_ty&&>
//移动语义
//定义Lambda一个接受std::string&& str 右值引用类型
auto func = [](std::string&& str) {
std::cout <<"Lambda : " << str << std::endl;
};
std::string name("cat");
//func(name); 出错, 左值需要转成右值
func(std::move(name));// = func(static_cast(name));
if (name.empty()) {
//name内容已经被移动了
std::cout << "name empty" << std::endl;
}
//移动构造函数
class A {
int x = 0;
public:
A(int _x) : x(_x) {
std::cout << "A() : x=" <<x<<std::endl;
}
A(const A& a) {//拷贝构造函数
x = a.x;
std::cout << "A(const A& a) : x=" << x << std::endl;
}
A(A&& a) noexcept { //移动构造函数
x = a.x;
a.x = 0;
std::cout << "A(A&& a) : x="<< x << std::endl;
}
~A() {
std::cout << "~A() : x="<<x<< std::endl;
}
};
{
A a(1);//打印输出: A() : x=1
A b = std::move(a); //打印输出: A(A&& a) : x=1
}
//与容器结合
{
std::cout << "vector" << std::endl;
std::vector vecDest;
std::vector vecSrc = { A(1), A(2), A(3) };
for (auto& elem : vecSrc) {
vecDest.push_back(std::move(elem));
}
}
{
std::cout << "list" << std::endl;
std::list lstDest;
std::list lstSrc = { A(1), A(2), A(3) };
for (auto& elem : lstSrc) {
lstDest.emplace_back(std::move(elem));
}
}
}