#C++ 笔记三

 七、异常处理

1.概念

异常是程序在执行期间产生的问题。

C++异常是指在程序运行时发生的特殊情况,比如下标越界等。

异常提供了一种转移程序控制权的方式。

2.抛出异常

throw语句的操作数可以是任意表达式,表达式结果的类型决定了抛出异常的类型。

抛出的异常是抛出到函数调用的位置。

#include <iostream>
using namespace std;


double division(double a,double b)
{
    if(b == 0)
    {
        string text("除数等于0!");
        throw text; // 抛出一个std::string
    }
    return a/b;
}

double input()
{
    cout << "input开始执行" << endl;
    double a;
    double b;
    cout << "请输入两个浮点型:" << endl;
    cin >> a >> b;
    double c = division(a,b);   // 1text 对象在这(无人处理)
    cout << "input执行结束" << endl;
    return c;
}

int main()
{
    cout << "程序开始执行" << endl;
    cout << input() << endl;    // 2text 对象在这(无人处理)

    cout << "程序执行结束" << endl;
    return 0;
}

3、捕获异常

try代码抛出一个异常,捕获异常使用catch代码块。


#include <iostream>
using namespace std;


double division(double a,double b)
{
    if(b == 0)
    {
        string text("除数等于0!");
        throw text; // 抛出一个std::string
    }
    return a/b;
}

double input()
{
    cout << "input开始执行" << endl;
    double a;
    double b;
    cout << "请输入两个浮点型:" << endl;
    cin >> a >> b;
    double c;
    try // 尝试执行代码块
    {
        c = division(a,b);
    }
    catch(string &e) // catch小括号中要写抛出异常的类型(类型跟抛出的类型不符合,会出现捕获不到的情况)
    {
        // 验证异常对象
        cout << e << endl;

        // 补救措施
        return 0;
    }

    cout << "input执行结束" << endl;
    return c;
}

int main()
{
    cout << "程序开始执行" << endl;
    cout << input() << endl;

    cout << "程序执行结束" << endl;
    return 0;
}

上述代码中可能会出现的几种情况:

1.无异常抛出,此时程序正常执行,不进入catch块

2.异常抛出,正确捕获,此时程序执行进入catch块。

3.异常抛出,错误捕获(捕获类型不对),此时程序仍然会向上抛出寻求正确捕获,如果每一层都没有正确捕获,此时程序仍然执行终止。

4、标准异常体系

C++给常见的异常类型进行了定义和分类,引入#include<stdexcept>头文件后进行使用。

这个体系还是太薄弱,因此可以对齐进行拓展。

自定义一个类型,继承自某个异常类型即可。

catch块可以匹配基类异常类型,提高匹配成功率,但是会降低匹配的精度

5、多重捕获

#include <iostream>
#include <stdexcept>
using namespace std;
// 继承自exception
class MyException:public exception
{
public:
    // 覆盖what函数
    // throw():异常规格说明
    // 表示此函数不会抛出任何的异常
   const char* what()const throw()
   {
        return "自定义类型异常";
   }
};

void show(string a,string b)
{
    if(a == "#" || b == "#")
    {
        throw MyException();
    }
    cout << a << b << endl;
}

int main()
{
    int type;
    cout << "请输入1或2或其他数字" << endl;
    cin >> type;
    try
    {
        if(type == 1)
        {
            string s = "fdfd";
            cout << s.at(100) << endl;
        }
        else if(type == 2)
        {
            throw overflow_error("异常2");
        }
        else
        {
            show("#","1211");
        }
    }
    catch(out_of_range &e)
    {
        cout << e.what() << endl;
    }
    catch(overflow_error &e)
    {
        cout << e.what() << endl;
    }
    catch(MyException &e)
    {
        cout << e.what() << endl;
    }
    cout << "程序正常运行结束" << endl;
    return 0;
}

6、粗略捕获

除了可以直接捕获异常类型外,也可以捕获异常的基类,甚至所有异常类型。

#include <iostream>
#include <stdexcept>
using namespace std;


int main()
{
    string s = "hello";
    try
    {
        cout << s.at(100) << endl;
    }
    catch(logic_error &e)
    {
        cout << e.what() << endl;
    }
    cout << "程序正常执行结束" << endl;

    return 0;
}

粗略捕获与多重捕获同时使用,此时要注意捕获的顺序,为派生类异常优先。

#include <iostream>
#include <stdexcept>
using namespace std;

int main()
{
    int type;
    cout << "请输入1或2、3或其他数字" << endl;
    cin >> type;
    try
    {
        if(type == 1)
        {
            throw invalid_argument("异常1");
        }
        else if(type == 2)
        {
            throw overflow_error("异常2");
        }
        else if(type == 3)
        {
            throw length_error("异常3");
        }
        else
        {
            throw out_of_range("异常4");
        }
    }
    catch(exception &e)
    {
        cout << "exception" <<e.what() << endl;
    }
    catch(out_of_range &e)
    {
        cout << e.what() << endl;
    }
    catch(overflow_error &e)
    {
        cout << e.what() << endl;
    }
    catch(length_error &e)
    {
        cout << e.what() << endl;
    }
    catch(invalid_argument &e)
    {
        cout << e.what() << endl;
    }

    cout << "程序正常运行结束" << endl;
    return 0;
}

使用...可以捕获所有类型,但是不推荐,更推荐使用或者建立标准异常体系。

#include <iostream>
#include <stdexcept>
using namespace std;
double division(double a,double b)
{
    if(b == 0)
    {
        string text("除数等于0!");
        throw text; // 抛出一个std::string
    }
    return a/b;
}


int main()
{
    int type;
    cout << "请输入1或2、3或其他数字" << endl;
    cin >> type;
    try
    {
        if(type == 1)
        {
            throw invalid_argument("异常1");
        }
        else if(type == 2)
        {
            throw overflow_error("异常2");
        }
        else if(type == 3)
        {
            throw length_error("异常3");
        }
        else if(type == 4)
        {
            division(3.3,0);
        }
        else
        {
            throw out_of_range("异常4");
        }
    }
    catch(exception &e)
    {
        cout << "exception" <<e.what() << endl;
    }
    catch(out_of_range &e)
    {
        cout << e.what() << endl;
    }
    catch(overflow_error &e)
    {
        cout << e.what() << endl;
    }
    catch(length_error &e)
    {
        cout << e.what() << endl;
    }
    catch(invalid_argument &e)
    {
        cout << e.what() << endl;
    }
    catch(...)
    {
       cout << "...异常" << endl;
    }

    cout << "程序正常运行结束" << endl;
    return 0;
}

八、智能指针

概念

堆内存的对象需要手动delete销毁,如果忘记使用delete销毁就会造成内存泄漏。

所以C++在ISO 98标准中引入了智能指针的概念,并在ISO11中趋于完善。

使用智能指针可以让堆内存对象具有占内存对象的特性,原理是给需要手动回收的堆内存对象套上一层栈内存的模板类对象即可。

C++中有四种智能指针:

  • auto_ptr(自动指针)(C++98,已废弃)
  • unique_ptr(唯一指针)(C++11)
  • shared_ptr(共享指针)(C++11)
  • weak_ptr(虚指针)(C++11)

使用智能指针的使用需要引入头文件#include<memory>

1 auto_ptr(熟悉)

 
 
 
#include <iostream>
#include <memory>
using namespace std;

class Test
{
private:
    string s;
public:
    Test(string s):s(s)
    {
        cout << s << "构造函数" << endl;
    }

    ~Test()
    {
        cout << s << "析构函数" << endl;
    }

    void show()
    {
        cout << s << "执行程序" << endl;
    }
};

int main()
{
    {
        Test *t1 = new Test("A");
        // 创建一个栈内存智能指针对象ap1
        auto_ptr<Test> ap1(t1); // ap1 管理t1

        // 取出被管理的堆内存对象,并调用show成员函数
        ap1.get()->show();
        // 释放ap1智能指针堆t1对象的控制权
        ap1.release();
        // 释放控制权并销毁资源对象
//        ap1.reset();

        // 创建B堆对象,A对象销毁,管理B对象
//        ap1.reset(new Test("B"));

//        delete t1;
        cout << "局部代码块执行结束" << endl;
    }   // 当ap1智能指针被销毁时,t1堆内存对象也销毁
    cout << "程序运行结束" << endl;
    return 0;
}

由于成员变量存在指针类型,因此拷贝构造函数与赋值运算符重载的使用会出现问题,与浅拷贝不同的是,auto_ptr的复制语义会引起对象控制权转移的问题。

 
 
 
#include <iostream>
#include <memory>
using namespace std;

class Test
{
private:
    string s;
public:
    Test(string s):s(s)
    {
        cout << s << "构造函数" << endl;
    }

    ~Test()
    {
        cout << s << "析构函数" << endl;
    }

    void show()
    {
        cout << s << "执行程序" << endl;
    }
};

int main()
{
    {
        auto_ptr<Test> ap1(new Test("A"));
        auto_ptr<Test> ap2(ap1);    // 调用拷贝构造函数
        cout << ap1.get() << " " << ap2.get() << endl; // 0 0x732758

        auto_ptr<Test> ap3 = ap2;   // 调用拷贝构造函数
        cout << ap1.get() << " " << ap2.get() << " " << ap3.get() << endl; // 0 0 0x1022758

        auto_ptr<Test> ap4;
        ap4 = ap3;  // 赋值运算符重载
        cout << ap1.get() << " " << ap2.get() << " " << ap3.get() << " " << ap4.get() << endl; // 0 0 0 0xf42758
    }
    cout << "程序运行结束" << endl;
    return 0;
}

2. unique_ptr(熟悉)

作为堆auto_ptr的改进,unique_ptr对其他持有的资源对象具有唯一的控制权,即不可以通过常规的复制语法转移或拷贝资源对象的控制权。

但是unique_ptr可以通过特殊的语法来实现控制权转移的效果。

 
 
 
#include <iostream>
#include <memory>
using namespace std;

class Test
{
private:
    string s;
public:
    Test(string s):s(s)
    {
        cout << s << "构造函数" << endl;
    }

    ~Test()
    {
        cout << s << "析构函数" << endl;
    }

    void show()
    {
        cout << s << "执行程序" << endl;
    }
};

int main()
{
    {
        unique_ptr<Test> up1(new Test("A"));
        unique_ptr<Test> up2(move(up1));    // 调用拷贝构造函数
        cout << up1.get() << " " << up2.get() << endl; // 0 0x732758

        unique_ptr<Test> up3 = move(up2);   // 调用拷贝构造函数
        cout << up1.get() << " " << up2.get() << " " << up3.get() << endl; // 0 0 0x1022758

        unique_ptr<Test> up4;
        up4 = move(up3);  // 赋值运算符重载
        cout << up1.get() << " " << up2.get() << " " << up3.get() << " " << up4.get() << endl; // 0 0 0 0xf42758
    }
    cout << "程序运行结束" << endl;
    return 0;
}

3. shared_ptr掌握)

unique_ptr对资源具有独占性,多个shared_ptr对象可以共享资源。

shared_ptr有两种创建方式:

两种创建方式的区别在于后者是一步实现(创建资源对象+关系绑定),前者分为两步完成(先创建资源,再绑定关系)。

后者的优点:

  • 完全性更好
  • 性能更好

后者的缺点:

  • 资源释放效率低

每多一个shared_ptr对资源进行管理,引用计数+1,每个指向该对象的shared_ptr智能指针对象在销毁时,引用计数将-1。最后一个shared_ptre对象销毁时,计数清零,资源对象销毁。

 
 
 
#include <iostream>
#include <memory>
using namespace std;

class Test
{
private:
    string s;
public:
    Test(string s):s(s)
    {
        cout << s << "构造函数" << endl;
    }

    ~Test()
    {
        cout << s << "析构函数" << endl;
    }

    void show()
    {
        cout << s << "执行程序" << endl;
    }
};

int main()
{
    shared_ptr<Test> sp3;
    {
        shared_ptr<Test> sp1 = make_shared<Test>("A");
        cout << "引用计数" << sp1.use_count() << endl; // 引用计数 1

        shared_ptr<Test> sp2(sp1); // 拷贝构造函数
        cout << "引用计数:" << sp2.use_count() << endl; // 引用计数:2

        sp3 = sp2;
        cout << "引用计数:" << sp3.use_count() << endl; // 引用计数:3
    }
    cout << "引用计数:" << sp3.use_count() << endl; // 1
    sp3.get()->show();
    cout << "程序运行结束" << endl;
    return 0;
}

4. weak_ptr熟悉)

weak_ptr是一个不控制资源对象的智能指针,也不会影响资源的引用计数,其主要的目的是协助shared_ptr的工作。

通过weak_ptr的构造函数,参数传入一个持有资源对象的shared_ptr对象或weak_ptr对象,即可创建。

weak_ptr与资源独享呈现弱相关性,因此不支持 get等函数直接操作资源对象。

 
 
 
#include <iostream>
#include <memory>
using namespace std;

class Test
{
private:
    string s;
public:
    Test(string s):s(s)
    {
        cout << s << "构造函数" << endl;
    }

    ~Test()
    {
        cout << s << "析构函数" << endl;
    }

    void show()
    {
        cout << s << "执行程序" << endl;
    }
};

int main()
{
    weak_ptr<Test>wp3;
    {
        shared_ptr<Test> sp1 = make_shared<Test>("A");
        weak_ptr<Test> wp1 = sp1;   // 构造函数
        cout << sp1.use_count() << endl;    // 1
        cout << wp1.use_count() << endl;    // 1

        weak_ptr<Test> wp2(wp1);
        cout << wp2.use_count() << endl;    // 1

        // 从weak_ptr中得到一个持有资源对象的shared_ptr对象
        shared_ptr<Test> sp2 = wp1.lock();
        cout << sp2.use_count() << endl; // 2

        wp3 = wp1;
        cout << wp3.use_count() << endl;    // 2
    }
    cout << wp3.use_count() << endl;    // 0

    if(wp3.expired())
    {
        cout << "无法使用lock函数" << endl;
    }

    cout << "程序运行结束" << endl;
    return 0;
}

5. 思考题了解)

手写一个共享指针SharedPtr。要求实现:

  • 构造函数
  • 拷贝构造函数
  • 复制运算符重载
  • get()函数
  • use_count函数
  • reset函数
  • 析构函数

 
 
 
#include <iostream>
#include <memory>
using namespace std;

template<class T>
class SharedPtr
{
private:
    T *res = NULL;  // 资源指针
    int *count = NULL;  // 引用计数

public:
    SharedPtr(T *t):res(t),count(new int(1)){}

    // 拷贝构造函数
    SharedPtr(const SharedPtr &sp):res(sp.res),count(sp.count)
    {
        (*count)++; // 计数+1
    }

    // 赋值运算符重载
    SharedPtr& operator =(const SharedPtr &sp)
    {
        if(&sp != this)
        {
            // 销毁原来的资源
            reset();
            res = sp.res;
            count = sp.count;
            (*count)++; // 计数+1
        }
        return *this;
    }

    void reset()
    {
        (*count)--; // 计数-1
        if(*count == 0)
        {
            delete res;
            delete count;
        }
        res = NULL;
        count = NULL;
    }

    T* get()const
    {
        return res;
    }

    int use_count()const
    {
        return *count;
    }

    ~SharedPtr()
    {
        reset();
    }
};



class Test
{
private:
    string s;
public:
    Test(string s):s(s)
    {
        cout << s << "构造函数" << endl;
    }

    ~Test()
    {
        cout << s << "析构函数" << endl;
    }

    void show()
    {
        cout << s << "执行程序" << endl;
    }
};

int main()
{
    SharedPtr<Test> sp1(new Test("A"));
    sp1.get()->show();
    cout << sp1.use_count() << endl;

    SharedPtr<Test> sp2(sp1);
    cout << sp2.use_count() << endl;

    SharedPtr<Test> sp3(new Test("B"));
    cout << sp3.use_count() << endl;    // 1

    sp3 = sp2;  // 赋值运算符重载
    sp3.get()->show();
    cout << sp3.use_count() << endl;

    return 0;
}

九、其他

1. nullptr(熟悉)

NULL在源码中就是一个0,因此可能会存在一些二义性的问题。

 
 
 
#include <iostream>
using namespace std;

void func(int a)
{
    cout << "a="<< a << endl;
}

void func(int *b)
{
    cout << "b=" << b << endl;
}

int main()
{
    func(NULL); // a=0

    return 0;
}

在C++11中使用nullptr代替NULL,作为空指针的表示方式。

 
 
 
#include <iostream>
using namespace std;

void func(int a)
{
    cout << "a="<< a << endl;
}

void func(int *b)
{
    cout << "b=" << b << endl;
}

int main()
{
    func(nullptr);  // b=0
    return 0;
}

2. 类型推导(熟悉)

使用auto关键字可以推导类型,C++11引入的。

 
 
 
#include <iostream>
using namespace std;


int main()
{
    auto i = 10;    // i的类型被推到为整形(int)
    cout << i << endl;

    auto i2 = 19.3; //  i2的类型被推导为浮点型(double)
    cout << i2 << endl;

    auto i3 = new auto(10); // i3 的类型被推导为int *
    cout << *i3 << endl;

    auto i4 = "hello";
    cout << i4 << endl;

    auto i5 = 'a';
    cout << i5 << endl;

    return 0;
}

decltype可以推导表达式的类型,需要注意的是,decltype只会分析表达式的类型,不会计算表达式的值。

 
 
 
#include <iostream>
using namespace std;


int main()
{
    auto x = 1; // 整形
    auto y = 2; // 整形

    decltype(x*y+123) z = 8888.87; // int * int + int = int
    cout << z << endl;

    return 0;
}

3. 初始化列表(掌握)

C++11中引入了列表初始化(初始化列表、通用统一初始化、一致性初始化)语法,可以使用{}对对象进行初始化。

 
 
 
#include <iostream>
#include <array>
#include <vector>
using namespace std;


class Student
{
private:
    string name;
    int age;
public:
    Student(string name,int age):name(name),age(age){}

    void show()
    {
        cout << name << " " << age<< endl;
    }

};

int main()
{
    array<int,5> arr1 = {1,2,3,4,5};
    for(int i:arr1)
    {
        cout << i << " ";   // 1 2 3 4 5
    }
    cout << endl;

    vector<int> vec1 = {1,2,3};
    for(int i:vec1)
    {
        cout << i << " ";   // 1 2 3
    }
    cout << endl;

    int arr3[3] = {1,2,4};
    for(int i:arr3)
    {
        cout << i << " ";   // 1 2 4
    }
    cout << endl;

    int a{};
    cout << a << endl;  // 0

    Student s = {"张三",10};
    s.show();

    return 0;
}

4. 面试题(重点)

【面试题】C++11学过的新特性有那些?

  1. 智能指针(后三个)
  2. array
  3. for-each
  4. 初始化列表
  5. nullptr
  6. 类型推导
  7. 继承构造
  8. override
  9. 类型转换(四种cast函数)

5. 进制输出(了解)

C++11可以对整数进行不同进制的输出。

 
 
 
#include <iostream>

using namespace std;



int main()
{
    // 为了区分不同的进制,可以增加进制显式功能,此功能设定持久
    cout << showbase;
    // 默认为10进制
    cout << dec << 1234 << endl; // 1234
    cout << oct << 1234 << endl; // 2322
    // 输出进制的设定是持久的
    cout << 9 << endl;  // 11
    cout << hex << 256 << endl;  // 100

    // 取消进制显式功能
    cout << noshowbase;
    cout << 16 << endl; // 10
    return 0;
}

6. 设定输出域宽度(了解)

可以使用setw()来制定一个整数或者一个字符串输出占用的域宽度。

  • 当设定域宽度小于数据本身时,仍然会显式为数据本身的宽度。
  • 当设定域宽度大于数据本身时,会显式未设定的宽度。

需要注意的是,输出域的宽度不是持久的,需要每次输出设定。

 
 
 
#include <iostream>
#include <iomanip>
using namespace std;


int main()
{
    // 仍然会按照实际的宽度输出
    cout << setw(5) << 123456 << setw(5) << 123456 << endl;

    // 使用输出域宽度
    cout << setw(10) << 123456 << setw(10) << 123456 << endl;

    cout << setw(10);
    cout << 123456 << endl;

    cout << 123456 << endl; // 输出域无效,因为输出域只能作用于下一行

    cout << setw(10);
    cout << 123456 << endl;

    return 0;
}

7. 文件IO(了解)

 
 
 
#include <iostream>
#include <fstream>  // 文件流头文件
using namespace std;


int main()
{
    // 文件输入流对象,用于读取数据
    // 参数1:读取的路径
    // 参数2:读取的方式二进制
    ifstream ifs("D:\\meeting_01.mp4",ios_base::binary);
    if(!ifs)
    {
        cout <<  "文件或路径不存在" << endl;
        return -1;
    }

    // 文件输出流对象,用于输出数据
    // 参数1:写出的路径
    // 参数2:写出方式二进制
    ofstream ofs("C:\\Users\\Administrator\\Desktop\\meeting_01.mp4",ios_base::binary);
    if(!ofs)
    {
        cout << "输出路径不存在" << endl;
        return -1;
    }
    // 把文件指针移动输入流尾部
    // 参数1:相对偏移量
    // 参数2:移动的位置
    ifs.seekg(0,ios::end);
    cout << "文件总大小:" << ifs.tellg() << "bytes" << endl;

    // 把文件指针移动回头部
    ifs.seekg(0,ios::beg);

    // 准备一个buffer
    char buf[2048];
    long long hasResd = 0;  // 已经读取的文件大小

    // 循环读写
    while(ifs)
    {
        // 读取固定的长度到buf中
        ifs.read(buf,2048);

        // 读取设定长度的数据到目标位置
        // 参数1:数据来源
        // 参数2:输出的数据量ifs.gcount()为上一次文件指针的偏移量
        ofs.write(buf,ifs.gcount());
        hasResd += ifs.gcount();
        cout << "已经拷贝的字节数:" << hasResd << endl;
    }

    // 收尾
    ifs.close();
    ofs.flush();    // 清空缓存区
    ofs.close();
    cout << "文件拷贝完成!!!!" << endl;

    return 0;
}

考试:

考试时长1.5小时

15~选择题(45)

5~简单题

10 填空题

1 编程题

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值