c++ 中范围的开始大括号处的存储分配?
在阅读 BRUCE ECKEL'S THINKING IN C++ 时,我遇到了以下文本
在 C++ 中,变量可以在作用域中的任何点定义,因此变量的存储可能会在其定义点之前才被定义。实际上,编译器更有可能遵循 c 中的分配作用域左大括号处的所有存储空间。
疑问:我猜它只用于在堆栈上分配存储,但我的疑问是编译器如何知道在达到其定义之前在 main (或其他 fn )内部定义了多少个对象(或什至不是一个)以便分配存储在范围的左大括号中。
while reading from BRUCE ECKEL'S THINKING IN C++..i came across the following text
In c++,a variable can be define at any point in a scope,so it might be seem that storage for variable may not be define until its point of definition .It's actually more likely that the compiler will follow in c of allocating all the storage for a scope at the opening brace of scope.
Doubt:I guess its only for storage allocating at stack but my doubt is how compiler get to know that how many objects(or not even a one) is defined inside the main(or other fn) before reaching to its definition in order to allocate storage at the opening brace of scope.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编译器可以在实际发出任何代码之前分析整个函数。通常,编译器将计算出每个花括号段需要多少存储空间,并在函数序言中添加一条汇编指令,以将堆栈指针调整那么多字节。
然而,实际初始化变量发生在代码中的适当位置。
The compiler can analyze the entire function before actually emitting any code. Typically, the compiler will work out, for each braced segment, how much storage is required, and add a single assembly instruction in the function prologue to adjust the stack pointer by that many bytes.
Actually initializing the variables, however, occurs at the appropriate point in the code.
编译器不一定会逐行解析代码。在编译期间,它将遍历整个范围/函数并确定要在堆栈上分配的内存量。
这就是编译存在的原因之一:)
The compiler does not necessarily parse the code in line by line fashion. During compilation it would have gone through the entire scope/function and determined the amount of memory to allocate on the stack.
That is one of the reason why compilation exists :)