C++堆和栈分配

这篇博客详细探讨了C++中堆和栈的区别,包括它们的定义方法和使用示例。通过源码分析,解释了堆和栈在内存分配上的特点,以及在实际编程中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、结论

1、用new或molloc分配的在堆上。
2、没用new或molloc,如果是在函数内定义的普通变量(非staic,非const),
那么是在栈上分配,如果做为类或结构体的成员,类或结构体在哪里分配,成员变量就在哪里分配。

二、定义方法

 1、基础类型
     int a; char c;
 2、指针类型
     int* a; char* c;
 3、对象
      Class1 c1; Struct1 s1;
      Class1 c1(args); Struct1 s1(args);
 3、对象指针类型
     Class1* c1 = new Class1;
     Struct1* s1 = new Struct1;
     Class1* c1 = new Class1(args);
     Struct1* s1 = new Struct1(args);

三、示例

1、源码

class HeapStackCls
{
public:
    int a;
};
struct HeapStackStruct
{
    int a;
};

class HeapStackTest
{
private:
    void Test2(int intArr[], int* intArrPtr, HeapStackStruct heapStackStruct, HeapStackStruct* heapStackStructPtr, HeapStackCls heapStackCls, HeapStackCls* heapStackClsPtr)
    {
        printf("%d %d %d %d %d %d\n", intArr, intArrPtr, &heapStackStruct, heapStackStructPtr, &heapStackCls, heapStackClsPtr);
        //int intArr[]和 int* intArrPtr都是传指针
        //heapStackStruct是在栈上新拷贝了对象,heapStackStructPtr是传了指针
        //heapStackCls是在栈上新拷贝了对象,heapStackClsPtr是传了指针
    }

public:
    void Test()
    {
        int a;
        int intArr[10] = {0,};
        int* intArrPtr = new int[10];
        HeapStackStruct heapStackStruct; //调用构造函数,在栈上分配
        HeapStackStruct* heapStackStructPtr;//HeapStackStruct* heapStackStruct只是在栈上分配一个指针
        heapStackStructPtr = new HeapStackStruct(); //调用new HeapStackStruct(),才会在堆上分配对象
        HeapStackCls heapStackCls; //调用构造函数,在栈上分配
        HeapStackCls* heapStackClsPtr;//调用new HeapStackCls(),才会在堆上分配对象
        heapStackClsPtr = new HeapStackCls();//调用new HeapStackCls(),才会在堆上分配对象
        printf("%d %d %d %d %d %d\n", intArr, intArrPtr, &heapStackStruct, heapStackStructPtr, &heapStackCls, heapStackClsPtr);
        Test2(intArr, intArrPtr, heapStackStruct, heapStackStructPtr, heapStackCls, heapStackClsPtr);
    }


};
2、输出
3536272 2405592 3536248 2405696 3536224 2405760
3536272 2405592 3535924 2405696 3535932 2405760
3、输出分析
  heapStackStruct和heapStackCls在调用Test2的时候,会在栈上重新创建对象(调用拷贝构造函数),
  所以Test2的heapStackStruct、heapStackCls的地址发生了变化。
  其他的分析可以看代码注释。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值