栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++内存逻辑一:对象释放

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++内存逻辑一:对象释放

局部对象释放顺序
#include
using namespace std;

class CreateAndDestroy{ 
    public: 
        CreateAndDestroy(int n) { no=n; cout<<"Object "< cout<<"Object "< 
    CreateAndDestroy*ptr; 
    CreateAndDestroy two(2);// 定义局部动态对象 two 
    { 
        CreateAndDestroy three(3);// 定义局部动态对象 three 
        ptr=new CreateAndDestroy(4); // 动态创建对象 
        static CreateAndDestroy five(5); // 定义局部静态对象 five 
    } 
    delete ptr;// 释放动态创建的对象 
    return 0; 
}

输出结果:
输出结果(省去末尾回车):
Object 1created!
Object 2created!
Object 3created!
Object 4created!
Object 5created!
Object 3destructed!
Object 4destructed!
Object 2destructed!
Object 5destructed!
Object 1destructed!

结论:
先释放main程序return前的对象,依次即3,4
之后局部动态(2)->局部静态(5)->全局变量(1)

包含类对象的类释放顺序

hello.h

#ifndef UNTITLED_HELLO_H
#define UNTITLED_HELLO_H
#include 
#include
using namespace std;

class hello {
public:
    hello(int n);
    ~hello();
    int no;
};

#endif //UNTITLED_HELLO_H
}

hello.cpp

#include "hello.h"

hello::hello(int n) {
    no=n; cout<<"hello "<
}

world.h

#ifndef UNTITLED_WORLD_H
#define UNTITLED_WORLD_H
#include "hello.h"
using namespace std;

class world {
public:
    world(int n);
    ~world();

    hello* hell;

    int no;
};

#endif //UNTITLED_WORLD_H

world.cpp

#include "world.h"

world::world(int n) {
    no=n; cout<<"world "<
    cout<<"world "< 

main.cpp

#include 
#include
using namespace std;

#include "world.h"
int main(){
    world* s= new world(1);
    delete s;
    int mm=1;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/994414.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号