c++11后类的三个基本原则变成了五个基本原则(C++类相关)

在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();
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值