堆栈vs堆C ++ [英] Stack vs Heap C++

查看:75
本文介绍了堆栈vs堆C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是对堆栈变量与堆变量的工作原理有一个简单的问题.据我了解,堆栈变量是在函数返回后将被删除的变量,而堆变量是持久的.但是我真正困惑的是如何在函数内部分配堆变量:

I just had a quick question about how stack variables versus heap variables work. As I understand it, stack variables are variables that after functions return will be deleted, and heap variables are persistent. But what I'm really confused about is how to allocate heap variables inside functions:

int MyObject::addObject(const char* a){
    MyObject newObject(a);
    return 0;
}

说我有一个MyObject的构造函数,即newObject(const char * a).然后在此函数中调用它时,在返回之后是否会删除新构造的newObject?如果是,那么如何在函数内分配给堆呢?如果没有,您以后如何清理内存?

Say that I have a constructor for MyObject that is newObject(const char * a). Then in this function when it is called, after the return does the newly constructed newObject get deleted? If yes, how can you allocate to the heap within a function then? If not, how do you cleanup your memory later?

此外,析构函数的确切作用是什么?何时调用它?

Furthermore, what exactly is the role of a destructor and when is it called?

推荐答案

MyObject的构造函数是MyObject(),而不是newObject().在您的示例中,newObject是变量的名称,而不是构造函数.

A constructor for the class MyObject is MyObject(), not newObject(). In your example, newObject is the name of your variable, not the constructor.

要在函数内部的堆上分配,您需要调用new运算符:

To allocate on the heap inside a function, you need to call the new operator:

int MyObject::addObject(const char* a){
    MyObject* newObject = new MyObject(a);
    //newObject is allocated on the heap

    //... Some more code...

    delete newObject;
    //you have to explicitly delete heap-allocated variables
    //if not, you get memory leaks
    return 0;
}

您的代码:

MyObject newObject(a);

创建一个名为newObject的自动存储(堆栈)MyObject,该存储将一直使用到最终声明它的作用域为止-即关闭}.

creates an automatic storage (stack) MyObject called newObject that lives until the scope it was declared in ends - i.e. closing }.

此外,析构函数的确切作用是什么?何时调用它?

Furthermore, what exactly is the role of a destructor and when is it called?

要清理内存,该内存分配有newnew[](或malloc)分配的类.当对象超出自动对象的范围时,或者显式调用动态对象的delete时,都会调用它.

To clean up memory the class allocated with new or new[] (or malloc) and it owns. It is called either when the object goes out of scope for automatic objects, or when you explicitly call delete for dynamic objects.

这篇关于堆栈vs堆C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆