开发者

Automatic variables in C++ [duplicate]

开发者 https://www.devze.com 2023-03-18 07:04 出处:网络
This question already has answers here: 开发者_JAVA百科 Closed 11 years ago. Possible Duplicate: In C++, why should new be used as little as possible?
This question already has answers here: 开发者_JAVA百科 Closed 11 years ago.

Possible Duplicate:

In C++, why should new be used as little as possible?

Where are automatic variables allocated in C++? On the stack or the heap?

Also, I read in 7.9 — The stack and the heap that all memory allocated on the stack is known at compile time. Is it true? Does it mean that only static memory allocation happens on the stack?

Also, please mention links, references to a a complete explanatory text about memory allocation in C++.


C++ does not have the concept of a stack or heap, it is an implementation detail as far as the language is concerned.

That being said, every implementation I know of uses the stack to manage the lifetime of local variables. However, many local variables may end up living entirely within registers and never touch the stack, and some local variables may be optimised out completely. Just because you declare an automatic variable doesn't mean that it will be put on the stack.

e.g.

int main()
{
    int x = rand();
    int y = 2;
    cout << x << y << endl;
    return 0;
}

In this code, with optimisations on, the variable y will almost certainly be removed completely and variable x will probably be given its own register. It's unlikely that either of those variables will ever exist on the stack.


Automatic (local) variables are not allocated on the heap. They will either live on the stack or in a register.

And yes, all stack allocations are know at compile time.

The link you referenced is actually a pretty good resource for describing how c++ handles memory.


Yes, auto vars are allocated, most commonly, on the stack (the C++ standard doesn't specify "stack" but it is safe enough to assume that).

You can use the stack to allocate dynamic memory with the alloca() function, but that is not very good practice, more on that in this question: Why is the use of alloca() not considered good practice?


In addition to locating some local variables in registers or on the stack, some compilers may choose to re-use specific registers or memory if it can be determined at compile time that the usable lifespan of an object is limited to regions of code.

For example,

{
int a;
// do something with a

int b;
// do something with b but nothing with a
}

The compiler will notice that a and b are the same size but a is not used anywhere during b's lifetime. The compiler will map both a and b to the same memory (stack or register), saving a bit of space.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号