zoukankan      html  css  js  c++  java
  • 函数堆栈

    做开发一定会调用到自己定义或者他人定义的函数,而函数调用必须通过堆栈来完成。

      函数堆栈实际上使用的是程序的堆栈内存空间,虽然程序的堆栈段是系统为程序分配的一种静态数据区,但是函数堆栈却是在调用到它的时候才动态分配的

    #include "stdafx.h"
    #include <iostream>
    using namespace std;
    
    class TestArrange {
    public:
        long m_lng;
        char m_ch1;
        TestArrange()
        {
            m_lng = 0;
            m_ch1 = 'a';
            m_int = 0;
            m_ch2 = 'a';
        }
        const int* GetIntAddr() { return &m_int; }
        const char* GetChar2Addr() { return &m_ch2; }
    
    private:
        int m_int;
        char m_ch2;
    };
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        TestArrange test;
        cout<<"Address of test object:"<<&test<<endl;
        cout<<endl;
        cout<<"Address of m_lng:"<<&(test.m_lng)<<endl;
        cout<<endl;
        printf("Address of m_ch1:%p
    ",&(test.m_ch1)); 
        /*cout<<""<<&(test.m_ch1)<<endl;*/
        cout<<endl;
        cout<<"Address of m_int:"<<test.GetIntAddr()<<endl;
        cout<<endl;
        cout<<"Address of m_ch2:"<<(void*)test.GetChar2Addr()<<endl;
        system("pause");
    
    
        return 0;
    }

    输出结果:

    Address of test object:0031FC9C

    Address of m_lng:0031FC9C

    Address of m_ch1:0031FCA0

    Address of m_int:0031FCA4

    Address of m_ch2:0031FCA8
    请按任意键继续. . .

      在C语言的格式化I/O中,常使用%p来输出内存的地址值;而在C++中,除了字符串的地址无法直接输出外,其他类型的地址都可以使用"&"输出。

      堆栈是自动管理的,也就是说局部变量的创建和销毁、堆栈的释放都是函数自动完成的,不需要程序猿的干涉。局部变量在程序执行流到达它的定义的时候创建,在退出其所在程序块的地方销毁,堆栈在函数退出的时候清退(还给程序堆栈段)。

      函数堆栈主要有三个用途:在进入函数前保存环境变量和返回地址,在进入函数时保存实参的拷贝,在函数体内保存局部变量。

  • 相关阅读:
    Python 面向对象3-类变量与实例变量
    Python面向对象2-类和构造方法
    Linux LVM动态扩容
    Anslib 使用错误归纳
    Linux Centos7安装最新anslib
    Linux 配置最新的epel源
    Linux centos7安装python3并且不影响python2
    docker compose启动服务超时重启记录
    spring cloud学习(三)使用Ribbon实现客户端负载均衡
    spring cloud 学习(二)关于 Eureka 的学习笔记
  • 原文地址:https://www.cnblogs.com/wiessharling/p/3259829.html
Copyright © 2011-2022 走看看