Destructor - copy constructor - assignment operator overloading - default constructor

By the following primer in an exercise, it may be more profound understanding, destructor, copy constructor, assignment operator overloading, default constructor.

But my results with primer exercise solutions which are not the same, may be different compilers causes.

// test1107.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

struct Exam{
    Exam(){ cout<<"Exam()"<<endl;} //默认构造函数
    Exam(const Exam&){ cout<<"Exam(const Exam&)"<<endl;} //复制构造函数
    Exam& operator= (const Exam&){ cout<<"Exam& operator"<<endl;return *this;} //赋值操作符
    ~Exam(){ cout<<"~Exam()"<<endl;}//析构函数
};

void func1(Exam a){}//形参为 exam的对象
void func2(Exam& b){}//形参为 exam的引用
Exam func3(){Exam obj;return obj;} //返回exam的对象


int main(){
    cout<<"--------------------1----------------"<<endl;
    Exam a; //调用默认的构造函数创建对象a
    cout<<"--------------------2----------------"<<endl;
    func1(a);// 调用复制构造函数,创建副本传递实参,撤销副本
    cout<<"--------------------3----------------"<<endl;
    func2(a); //形参为引用,无需传递实参
    cout<<"--------------------4----------------"<<endl;
    a = func3(); //调用默认构造函数创建局部对象,
                //用复制构造函数返回对象副本
                //调用析构函数撤销局部对象
                //调用赋值函数赋值
                //调用析构函数撤销副本
    cout<<"--------------------5----------------"<<endl;
    Exam *b = new Exam(); //调用默认构造函数创建对象
    cout<<"--------------------6----------------"<<endl;
    vector<Exam> exec(3); //调用默认构造函数创建对象
                        //调用赋值构造函数将临时对象复制到每个元素
                        //调用析构函数撤销

                        //重复三次
    cout<<"--------------------7----------------"<<endl;
    delete b; //调用析构,撤销p
    cout<<"--------------------8----------------"<<endl;
    system("pause");
}

Execution results are as follows:

Reproduced in: https: //my.oschina.net/u/204616/blog/545105

Guess you like

Origin blog.csdn.net/weixin_34187822/article/details/91989463
Recommended