《C++ Primer Plus》学习笔记 — 智能指针模板和optional类

本文详细介绍了C++中的智能指针,包括auto_ptr、unique_ptr、shared_ptr和weak_ptr的特性与用法,重点讲解了shared_ptr的aliasing constructor、owner_before和owner_less,以及weak_ptr的作用。此外,还探讨了optional类如何提高代码可读性,以及in_place_t的使用。
摘要由CSDN通过智能技术生成

一、auto_ptr 和 unique_ptr

前面我们了解过,unique_ptr要优于auto_ptr。而且auto_ptr已经为C++标准所弃用。那么这里unique_ptr的优越性主要体现在:禁止左值引用的对象所有权隐式转移,仅能使用std::move函数转移所有权,允许右值引用的对象所有权转移。

#include <iostream>
using namespace std;

unique_ptr<string> test(const char *_pStr)
{
   
	unique_ptr<string> temp(new string(_pStr));
	return temp;
}

int main()
{
   
	// unique_ptr
	unique_ptr<string> pTestUnique(new string("unique_ptr"));
	//unique_ptr<string> pTestUniqueCopy = pTestUnique; invalid assignment
	cout << "*pTestUnique = " << *pTestUnique << endl;

	unique_ptr<string> pTestUniqueRvalue = test("unique_ptr with rValue");
	cout << "*pTestUniqueRvalue = " << *pTestUniqueRvalue << endl;

	unique_ptr<string> pTestUniqueMove = move(pTestUnique);
	cout << "*pTestUniqueMove = " << *pTestUniqueMove << endl;

	// auto_ptr
	auto_ptr<string> pTestAuto(new string("auto_ptr"));
	auto_ptr<string> pTestAutoCopy = pTestAuto;
	cout << *pTestAuto << endl;
}

在这里插入图片描述

二、shared_ptr 和 weak_ptr

1、aliasing constructor

除了我们前面学习过的指定deleterallocator的构造函数,shared_ptr还有一种特殊的构造函数 — aliasing constructor

template <class _Ty2>
shared_ptr(const shared_ptr<_Ty2>& _Right, element_type* _Px) noexcept {
   
    // construct shared_ptr object that aliases _Right
    this->_Alias_construct_from(_Right, _Px);
}

通常情况下,我们会用一个智能指针来管理一个对象。然而,aliasing constructor给我们提供了部分对象管理的功能:

#include <iostream>
using namespace std;

struct STRUCT_Test
{
   
	int m_i;
	string m_str;
};

int main()
{
   
	auto pTest = std::make_shared<STRUCT_Test>();
	std::shared_ptr<int> pTestAlias(pTest, &pTest->m_i);
}

那么这么做的用意何在呢?考虑多继承情况:

#include <iostream>
using namespace std;

class CLS_Base1
{
   
public:
	int m_i1;

	virtual ~CLS_Base1()
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值