zoukankan      html  css  js  c++  java
  • C++ 小心你的析构函数不会执行

    #include <string>
    #include <iostream>
    using namespace std;
    class Student
    {
    public:
        int num ;
        string strname;
        Student(int num,string name)
        {
            this->num=num;
            this->strname=name;
        }
        ~Student()
        {
            cout<<"num:"<<this->num<<"name"<<this->strname<<endl;
        }
    };

    int _tmain(int argc, _TCHAR* argv[])
    {   

        Student stu1(1,"Li Ming");//对象定义在栈上,所以程序结束时会自动析构哦;
        Student *pstu2=new Student(2,"Wang qing");//对象定义在堆上,除非delete否则不析构

     //(1)

        return 0;

    }

    上面两种定义都定义了对象,但是执行结果是下面的:


    上面没有调用delete删除堆上的对象,所以程序即使结束了,对象是不会自动析构的,这就产生了垃圾;如何这些是一些资源文件或者内核对象,你的程序迟早挂掉;

    在(1)处加入    delete pstu2;


    所以,使用类定义的对象是能够自动析构的;使用类通过new出来的对象,是需要delete的,你不delete,你SOCKET、多线程编程会出问题的;






  • 相关阅读:
    Dockerize a .NET Core application
    Images之管理image
    Images之Dockerfile中的命令2
    Images之Dockerfile中的命令1
    Docker Builders:Builder pattern vs. Multi-stage builds in Docker
    Images之multi-stage builds
    Images之base image
    Images之Dockerfiles
    Docker 开发最佳实践
    Docker 开发概述
  • 原文地址:https://www.cnblogs.com/javawebsoa/p/3047780.html
Copyright © 2011-2022 走看看