啥是“合成构造函数”
在 C++ 中,当你没有显式定义某些构造函数时,编译器会为你自动生成一些“合成构造函数”
这些函数包括:
- 默认构造函数
- MyClass()
- 拷贝构造函数
- MyClass(const MyClass& other)
- 移动构造函数
- MyClass(MyClass&& other)
- 拷贝赋值运算符
- MyClass& operator=(const MyClass& other)
- 移动赋值运算符
- MyClass& operator=(MyClass&& other)
- 析构函数
- ~MyClass()
移动构造是如何实现的
移动构造函数会将资源从源对象“转移”到新对象,而不进行深拷贝
MyClass(MyClass&& other) noexcept : data(std::move(other.data)) {}
为什么移动构造函数需要 std::move
移动构造函数的目的是转移资源,而不是复制资源;当调用 std::move 时,实际上是通知编译器,希望将一个对象的资源 从一个地方“转移”到另一个地方;在移动语义下,源对象的资源可以被重新利用,而不必进行大量的拷贝
std::move 实现的逻辑
std::move 并不会移动任何东西,它只是将左值转换成右值引用类型,这样就可以调用 移动构造函数 或 移动赋值运算符 了
// std::move 实现(C++标准库中实际上更复杂,但这个是简化的)
template <typename T>
constexpr T&& move(T& t) noexcept {
return static_cast<T&&>(t); // 将左值转换为右值引用
}
移动构造的示例
下面是一个简单的vector实现移动构造的示例:
template <typename T>
class vector {
public:
T* data; // 指向数据的指针
size_t size; // 向量的大小
size_t capacity; // 向量的容量
// 移动构造函数
vector(vector&& other) noexcept
: data(other.data), // 直接转移数据指针
size(other.size), // 转移大小
capacity(other.capacity) // 转移容量
{
// 使源对象变为空
other.data = nullptr;
other.size = 0;
other.capacity = 0;
}
~vector() {delete[] data;}
}
这样我们就可以通过移动std::move来调用到移动构造函数了
std::vector<int> vec1 = {1, 2, 3, 4, 5};
std::vector<int> vec2 = std::move(vec1); // 调用移动构造函数
258

被折叠的 条评论
为什么被折叠?



