一、结论
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);
}
public:
void Test()
{
int a;
int intArr[10] = {0,};
int* intArrPtr = new int[10];
HeapStackStruct heapStackStruct;
HeapStackStruct* heapStackStructPtr;
heapStackStructPtr = new HeapStackStruct();
HeapStackCls heapStackCls;
HeapStackCls* heapStackClsPtr;
heapStackClsPtr = 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的地址发生了变化。
其他的分析可以看代码注释。