成员函数是否将其本地数据放在堆栈中? [英] Do memberfunctions put their local data on the stack?

查看:58
本文介绍了成员函数是否将其本地数据放在堆栈中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的问题,关于对象的范围和成员函数的范围。



程序可见的计算机内存基本上分为两个零件:

1.堆栈

2.堆积



堆栈就像堆一样:你将东西置于其上并以相反的顺序移除东西。

堆就像一个带抽屉的柜子。你必须寻找一个空的东西。

只要程序运行,抽屉就可以满了。



这里我有一个范围:



I have a simple question about the scope of a object and the scope inside of the member functions.

Computer memory visible for a program is basicly devided in two parts:
1. the stack
2. the heap

The stack act like pile a dishes: You put things on top of it and remove things in reverse order.
The heap is like a cabinet with drawers. You have to look for an empty one to put a thing in.
A drawer can be full as long as the program runs.

Here i have a scope:

{
  MyClassType *pObjOnHeap;
  {
     MyClassType objOnStack;
     objOnStack.sayHello();
   
     pObjOnHeap = new MyClassType;
     pObjOnHeap->sayHello();
  }
  delete pObjOnHeap;
}



objOnStack 在堆栈中创建其数据。

pObjOnHeap 在堆中创建其数据。

但是他们的成员函数都会在堆栈中推送和弹出它们的本地数据。 />
这是对的吗?



我的尝试:



我读过Bjarne Stroustrup的The C ++ Programming Language 4th edition。


The objOnStack is created its data in the stack.
The pObjOnHeap is created its data in the heap.
But both theirs member-functions push and pop their local data on the stack.
Is this right?

What I have tried:

I read "The C++ Programming Language 4th edition" by Bjarne Stroustrup.

推荐答案

取决于。以下示例将列出对象的地址和成员变量,显示它们的创建位置:

It depends. The following sample will list the addresses of the objects and the member variables, showing where they are created:
class CObject
{
public:
    void Method()
    {
        printf("\n\tIn Method\n");
        int localVar; // stack variable
        localVar = 5;
        printf("\t\tlocalVar: %p\n", &localVar);
        int* heapVar = new int[20]; // heap variable
        heapVar[1] = 100;
        printf("\t\theapVar: %p\n", heapVar);
        //delete[] heapVar; --> don't delete so next call to new will use new heap address
    }
};

int result = 0;
printf("result: %p\n", &result);
CObject localObject; // object on the stack
printf("\nlocalObject: %p\n", &localObject);
localObject.Method();

CObject* heapObject = new CObject(); // object on the heap
printf("\nheapObject: %p\n", heapObject);
heapObject->Method();



您应该看到在方法中创建的局部变量之间的差异(在两种情况下) 和堆变量。


这篇关于成员函数是否将其本地数据放在堆栈中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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