c++ - C++中的内存分配

标签 c++

我对 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/

相关文章:

c++如何对结构数组进行排序

c++ - 在 Ubuntu 上通过 C++ 的 system() 将输出与 SIPp 远程命令混淆

c++ - 是否可以触发由 1 发送触发的 2 接收回调?

c++ - 单元测试需要很长时间才能运行。瓦尔格林德问题?冠状病毒问题?

c++ - 与 boost::interprocess 共享内存时从 std::string 转换为 "MyShmString"

c++ - 如何在 C++ 中转发类的声明?

c++ - 非模板类的模板成员作为好友

c++ - 自动引用计数系统中的赋值是线程安全的吗?

c++ - BOOST 正则表达式全局搜索行为

C++ 使用字符串项在列表中查找结构?