《C++ Primer Plus》学习笔记 — 智能指针模板和optional类
一、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
除了我们前面学习过的指定deleter、allocator的构造函数,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()