在C++11后对类的定义又加了以下两个基本原则:
4,5、可以对拷贝构造函数和operator=进行右值引用进行重载
除此之外还应该注意几下几点:
1、new指针重新定位不进行释放会造成内存泄漏
2、move:将原来的b左值引用转化成右值引用
std::vector<int> a;
for(int i = 0;i < 10; ++i) a.push_back(i);
auto b = a;
auto& c = b;
std::vector<int> d = std::move(b);
3、对于临时变量虽然不能获取它的引用或是可以获取它的const引用
4、auto& c = b调用的是拷贝构造函数
5、可以重载右值引用的拷贝构造函数,让右值的全部内存资源清空都移到左值来
完整代码例子:
#include <cassert>
#include <iostream>
#include <vector>
class RuleOfFive {
public:
RuleOfFive(const RuleOfFive &rhs) : m_value(new int(*(rhs.m_value))) {}
RuleOfFive(RuleOfFive&& rhs) = delete;
RuleOfFive &operator=(const RuleOfFive &rhs) {
*m_value = *(rhs.m_value);
return *this;
}
RuleOfFive& operator=(RuleOfFive&& rhs) = delete;
~RuleOfFive() { delete m_value; }
RuleOfFive() : m_value(new int(10)) {}
void print() const {
//assert(m_value);
if(m_value)
std::cout << *m_value << std::endl;
}
private:
int *m_value;
};
//RuleOfFive::RuleOfFive(RuleOfFive&& rhs) {
// m_value = rhs.m_value;
// rhs.m_value = nullptr;
//}
int print(const int& a) {
std::cout << a << std::endl;
}
int main() {
int abc = 10;
const int& bc = abc;
print(abc);
print(bc);
print(10);
// && and move
std::vector<int> a;
for(int i = 0; i < 10; ++i) a.push_back(i);
RuleOfFive b;
auto& c = b;
// RuleOfFive&&
RuleOfFive e = b;
RuleOfFive d = std::move(b);
e = std::move(e);
//b.print();
}