int i = 42; int &r = i; //r引用i int &r2 = i*2; //错误,i*2是一个右值 int &&rr = i; //错误,不能将一个右值引用绑定到一个左值上 int &&rr2 = i*2; //正确,将rr2绑定到一个乘法结果上 const int &r3 = i*2; //正确,将一个常量引用绑定到一个右值上
int &&rr3 = std::move(rr2);
#include <iostream>
#include <algorithm>
class MemoryBlock
{
public:
// 构造函数
explicit MemoryBlock(size_t length) : _length(length) , _data(new int[length]) {}
// 析构函数
~MemoryBlock()
{
if (_data != nullptr) delete[] _data;
}
// 拷贝赋值运算符
MemoryBlock& operator=(const MemoryBlock& other)
{
if (this != &other)
{
delete[] _data;
_length = other._length;
_data = new int[_length];
std::copy(other._data, other._data + _length, _data);
}
return *this;
}
// 拷贝构造函数
MemoryBlock(const MemoryBlock& other)
: _length(0)
, _data(nullptr)
{
*this = other;
}
// 移动赋值运算符,通知标准库该构造函数不抛出任何异常(如果抛出异常会怎么样?)
MemoryBlock& operator=(MemoryBlock&& other) noexcept
{
if (this != &other)
{
delete[] _data;
// 移动资源
_data = other._data;
_length = other._length;
// 使移后源对象处于可销毁状态
other._data = nullptr;
other._length = 0;
}
return *this;
}
// 移动构造函数
MemoryBlock(MemoryBlock&& other) noexcept
_data(nullptr)
, _length(0)
{
*this = std::move(other);
}
size_t Length() const
{
return _length;
}
private:
size_t _length; // The length of the resource.
int* _data; // The resource.
};
class Foo{
public:
Foo() = default;
Foo(const Foo&);
// 为定义移动构造函数
};
Foo x;
Foo y(x); //调用拷贝构造函数
Foo z(std::move(x)); //调用拷贝构造函数,因为未定义移动构造函数
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有