一、异常
1、C语言传统处理错误的方式:终止程序,退出函数,返回错误码。
而C++更喜欢用异常处理,当一个函数发现自己无法处理的错误时就可以抛出异常,让函数的直接或间接调用者处理这个错误。
#include<iostream>
#include<string>
#include<windows.h>
using namespace std;
double Division(int a, int b)
{
// 当b == 0时抛出异常,且直接跳到catch的位置,避免了层层向上返回
if (b == 0)
{
throw "Division by zero condition!";
}
// 抛出的异常对象是一个临时拷贝对象
// if (b == 0)
// {
// string s("Division by zero condition!");
// throw s;
// }
else
{
return ((double)a / (double)b);
}
}
void Func()
{
try {
int len, time;
cin >> len >> time;
cout << Division(len, time) << endl;
}
catch (const char* errmsg) {
cout << errmsg << endl;
}
cout << "yyyyyyyyy" << endl;
}
int main()
{
try {
Func();
}
catch (int errmsg) {
cout << errmsg << endl;
}
catch (const char* errmsg) {
cout << errmsg << endl;
}
//这个拷贝的临时对象会在被catch以后销毁。
// catch (const string& errmsg) {
// cout << errmsg << endl;
// }
cout << "xxxxxxxxxx" << endl;
// catch (...) { // 任意类型
// //防止因抛不规范异常的程序终止
// cout << "未知异常" << endl;
// }
return 0;
}
3、异常的抛出和匹配规则
// 这里表示这个函数会抛出A/B/C/D中的某种类型的异常
void fun() throw(A,B,C,D);
// 这里表示这个函数只会抛出bad_alloc的异常
void* operator new (std::size_t size) throw (std::bad_alloc);
// 这里表示这个函数不会抛出异常
void* operator delete (std::size_t size, void* ptr) throw();
// C++11 中新增的noexcept,表示不会抛异常
thread() noexcept;
thread(thread&& x) noexcept;
6、异常安全:
1.)构造函数完成对象的构造和初始化,最好不要在构造函数中抛出异常,否则可能导致对象不完整或没有完全初始化
2.)析构函数主要完成资源的清理,最好不要在析构函数内抛出异常,否则可能导致资源泄漏(内
存泄漏、句柄未关闭等)
3.)C++中异常经常会导致资源泄漏的问题,比如在new和delete中抛出了异常,导致内存泄漏,在lock和unlock之间抛出了异常导致死锁,C++经常使用RAII来解决以上问题,关于RAII
我们智能指针这节进行讲解。
7、异常的优缺点:
C++异常的优点:
1. 清晰准确的展示出错误的各种信息。
2. 返回错误码的弊端:在函数调用链中,深层的函数返回了错误,需要层层返回错误,最外层才能拿到错误。
3. 很多的第三方库都包含异常,比如boost、gtest、gmock等等常用的库,那么我们使用它们
也需要使用异常。
4. 部分函数使用异常更好处理(比如构造函数没有返回值,不方便使用错误码方式处理。比如T & operator这样的函数,如果pos越界了只能使用异常或者终止程序处理,没办法通过返回值表示错误。)
C++异常的缺点:
1. 异常会导致程序的执行流乱跳,并且非常的混乱,并且是运行时出错抛异常就会乱跳。这会
导致我们跟踪调试时以及分析程序时,比较困难。
2. 异常会有一些性能的开销。当然在现代硬件速度很快的情况下,这个影响基本忽略不计。
3. C++没有垃圾回收机制,资源需要自己管理。有了异常非常容易导致内存泄漏、死锁等异常
安全问题。
4. C++标准库的异常体系定义得不好,导致大家各自定义各自的异常体系,非常的混乱。
5. 异常尽量规范使用,否则后果不堪设想,随意抛异常,外层捕获的用户苦不堪言。所以异常
规范有两点:a.抛出异常类型都继承自一个基类。b.函数是否抛异常、抛什么异常,都使用 func() throw(); 的方式规范化.
二、智能指针
1、智能指针的使用及原理:利用对象的生命周期控制释放资源。
好处:
不需要显式地释放资源。
对象所需的资源在其生命期内始终保持有效
2、智能指针的模拟实现:
1、)auto_ptr
弊端:管理权转移导致被拷贝对象悬空。
#pragma once
#include<iostream>
using namespace std;
namespace star
{
template<class T>
class auto_ptr
{
public:
auto_ptr(T* ptr)
:_ptr(ptr)
{}
//拷贝构造,但是会将被拷贝对象置空,再次访问被拷贝对象程序会崩溃(管理权转移)
auto_ptr(auto_ptr<T>& ap)
:_ptr(ap._ptr)
{
ap._ptr = nullptr;
}
auto_ptr operator=(auto_ptr<T>& ap)
{
//自己给自己赋值
if (_ptr == ap._ptr)
return *this;
_ptr = ap._ptr;
ap._ptr = nullptr;
}
~auto_ptr()
{
cout << "delete:" << _ptr << endl;
delete _ptr;
}
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
private:
T* _ptr;
};
};
2、)unique_ptr
原理:简单粗暴 -- 防拷贝
namespace star
{
template<class T>
class unique_ptr
{
public:
unique_ptr(T* ptr)
:_ptr(ptr)
{}
~unique_ptr()
{
cout << "delete:" << _ptr << endl;
delete _ptr;
}
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
unique_ptr(unique_ptr<T>& up) = delete;
unique_ptr operator=(unique_ptr<T>& up) = delete;
private:
T* _ptr;
};
};
3、)shared_ptr
原理:是通过引用计数的方式来实现多个shared_ptr对象之间共享资源。
namespace star
{
template<class T>
class shared_ptr
{
public:
shared_ptr(T* ptr = nullptr)
:_ptr(ptr)
, _pcount(new int(1))
{}
shared_ptr(const shared_ptr<T>& sp)
:_ptr(sp._ptr)
, _pcount(sp._pcount)
{
++(*_pcount);
}
shared_ptr<T>& operator=(const shared_ptr<T>& sp)
{
//自己给自己赋值
if (_ptr == sp._ptr)
return *this;
if (--(*_pcount) == 0)
{
delete _ptr;
delete _pcount;
}
_ptr = sp._ptr;
_pcount = sp._pcount;
++(*_pcount);
return *this;
}
~shared_ptr()
{
if (--(*_pcount) == 0)
{
cout << "delete:" << _ptr << endl;
delete _ptr;
delete _pcount;
}
}
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
int use_count()const
{
return *_pcount;
}
T* get()const
{
return _ptr;
}
private:
T* _ptr;
int* _pcount;
};
};
但是shared_ptr会发生循环引用的问题。
struct Node
{
A _val;
star::shared_ptr<Node> _next;
star::shared_ptr<Node> _prev;
};
int main()
{
// 循环引用
star::shared_ptr<Node> sp1(new Node);
star::shared_ptr<Node> sp2(new Node);
sp1->_next = sp2;
sp2->_prev = sp1;
return 0;
}
4、)weak_ptr:解决循环引用问题。
注:
weak_ptr不是RAII智能指针,专门用来解决shared_ptr循环引用问题。
weak_ptr不增加引用计数,可以访问资源,不参与资源释放的管理。
namespace star
{
template<class T>
class weak_ptr
{
public:
weak_ptr()
:_ptr(nullptr)
{}
weak_ptr(const shared_ptr<T>& sp)
:_ptr(sp.get())
{}
weak_ptr<T>& operator=(const shared_ptr<T>& sp)
{
_ptr = sp.get();
return *this;
}
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
private:
T* _ptr;
};
};
5、)定制删除器:用智能指针管理非new出来的对象
用法:
template<class T>
struct DeleteArray
{
void operator()(T* ptr)
{
delete[] ptr;
}
};
// 定制删除器
int main()
{
std::shared_ptr<A> sp1(new A[10], DeleteArray<A>());
std::shared_ptr<A> sp2((A*)malloc(sizeof(A)), [](A* ptr) {free(ptr); });
std::shared_ptr<FILE> sp3(fopen("Test.cpp", "r"), [](FILE* ptr) {
cout << "fclose:" << ptr << endl;
fclose(ptr);
});
std::shared_ptr<A> sp1(new A);
return 0;
}
模拟实现:
namespace star
{
template<class T>
class shared_ptr
{
public:
shared_ptr(T* ptr = nullptr)
:_ptr(ptr)
, _pcount(new int(1))
{}
template<class D>
shared_ptr(T* ptr, D del)
: _ptr(ptr)
, _pcount(new int(1))
, _del(del)
{}
shared_ptr(const shared_ptr<T>& sp)
:_ptr(sp._ptr)
, _pcount(sp._pcount)
{
++(*_pcount);
}
shared_ptr<T>& operator=(const shared_ptr<T>& sp)
{
//自己给自己赋值
if (_ptr == sp._ptr)
return *this;
if (--(*_pcount) == 0)
{
delete _ptr;
delete _pcount;
}
_ptr = sp._ptr;
_pcount = sp._pcount;
++(*_pcount);
return *this;
}
~shared_ptr()
{
if (--(*_pcount) == 0)
{
cout << "delete:" << _ptr << endl;
_del(_ptr);
delete _pcount;
}
}
T& operator*()
{
return *_ptr;
}
T* operator->()
{
return _ptr;
}
int use_count()const
{
return *_pcount;
}
T* get()const
{
return _ptr;
}
private:
T* _ptr;
int* _pcount;
function<void(T*)> _del = [](T* ptr) {delete ptr; };
};
};