我对 C++ 中的内存分配感到困惑。谁能指导我以下代码段中的每个变量的分配位置。我如何确定在堆栈上分配了什么以及在堆上分配了什么。有没有什么好的网络引用资料可以学习这个。
class Sample {
private:
int *p;
public:
Sample() {
p = new int;
}
};
int* function(void) {
int *p;
p = new int;
*p = 1;
Sample s;
return p;
}
最佳答案
如果它是通过 new
创建的,它就在堆中。如果它在函数内部,并且不是 static
,那么它就在堆栈上。否则,它位于全局(非堆栈)内存中。
class Sample {
private:
int *p;
public:
Sample() {
p = new int; // p points to memory that's in the heap
}
// Any memory allocated in the constructor should be deleted in the destructor;
// so I've added a destructor for you:
~Sample() { delete p;}
// And in fact, your constructor would be safer if written like this:
// Sample() : p(new int) {}
// because then there'd be no risk of p being uninitialized when
// the destructor runs.
//
// (You should also learn about the use of shared_ptr,
// which is just a little beyond what you've asked about here.)
};
int* function(void) {
static int stat; // stat is in global memory (though not in global scope)
int *p; // The pointer itself, p, is on the stack...
p = new int; // ... but it now points to memory that's in the heap
*p = 1;
Sample s; // s is allocated on the stack
return p;
}
}
int foo; // In global memory, and available to other compilation units via extern
int main(int argc, char *argv[]) {
// Your program here...
关于c++ - C++中的内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4643425/