3

假设我在动态内存(新)中有一个对象,并且在它的一个函数中,它有

int Obj1::Add(int a, int b)
{
    int c = a + b;
    return c;
}

c (和 a 和 b...) 在堆栈上吗?或在我的对象的动态内存中。只是好奇:)谢谢

4

5 回答 5

3

所有这些都将在堆栈上。ab传递参数,因此即使原始文件在堆中,也会在堆栈上制作副本。如果您通过引用传递,则可能是另一回事,因为实际发送的东西(“在引擎盖下”)将更像是指向原始对象的指针。

对于c,因为它是一个局部变量,所以它也在堆栈上。

这当然是假设您的实现甚至使用了堆栈,并且优化并不仅仅是将它们存储到寄存器中。这完全取决于实施。

于 2012-04-11T08:37:40.197 回答
3

C++ 标准中没有明确提及术语“堆栈”或“堆”。相反,需要一个 C++ 编译器来根据特定的“存储持续时间”来实现:

C ++调用堆栈不是标准的?

但是对于今天的处理器和编译器的实际用途,您通常可以假设 a/b/c 位于堆栈或寄存器中。

于 2012-04-11T08:46:55.067 回答
3

It's really up to the compiler. On a Sparc, all three will be in registers, and I would expect this to be the most frequent case. Only on an Intel 32 bit (or 16 bit, if you go back in time) would a and b be on the stack.

None of which is relevant to much of anything. Concerning the key point of your question (I think): none of them will be part of the object referenced by this. However the compiler organizes things, the three variables will be somewhere else than the object. Even if the object itself is on the stack, and you're on an Intel architecture where arguments, etc. are also on the stack, the object and the variables will be in different places on the stack.

于 2012-04-11T08:53:24.383 回答
1

ab并且c在堆栈上(或可能在寄存器中)。

于 2012-04-11T08:37:13.347 回答
0

它们都在堆栈上。但是,将 c 返回给调用者仍然是安全的,因为会生成一个副本。

于 2012-04-11T08:38:04.287 回答