简体   繁体   English

C ++分配标准?

[英]C++ allocation standard?

Let's assume I have a class Foo, and a function Bar 假设我有一个Foo类和一个功能栏

void Bar(void)
{
Foo a();
}

Does that mean that a will necessarely be NOT allocated in the main memory ? 这是否意味着不必在主内存中分配a? Or does this depend on compilers so the compiler may allocate memory and result in the same thing as if we wrote Foo* a=new Foo 还是这取决于编译器,所以编译器可能会分配内存并产生与我们编写Foo* a=new Foo相同的结果

Foo a(); is a function declaration. 是一个函数声明。 It should be Foo a ; 应该是Foo a ; And a is in the memory of stack. 并且a在堆栈的内存中。

The term you're looking for is an automatic variable . 您要查找的术语是一个自动变量 This means that the object contained in that variable is guaranteed to be destroyed at the end of the scope automatically . 这意味着该变量中包含的对象可以保证在作用域结束时自动销毁。

When you use new , the object is destroyed only when you delete it explicitly (or by explicitly using a mechanism that takes care of destroying it, like smart pointers). 使用new ,仅在显式delete对象时(或通过显式使用用于销毁对象的机制,如智能指针)将其销毁。 In other words, the lifetime is manually managed. 换句话说,寿命是手动管理的。

Of course, automatic lifetime semantics are not the same as manual semantics under any circumstance. 当然,自动生存期语义在任何情况下都与手动语义不同。 That being said, the storage location (stack, heap, registers, or something else) in both cases is irrelevant. 话虽如此,两种情况下的存储位置(堆栈,堆,寄存器或其他内容)都是无关紧要的。

Technically, if a fits in a register, it could end up using "no memory" at all. 从技术上讲,如果a寄存器适合寄存器,则最终可能会完全使用“无内存”。 Otherwise, it will be allocated on the stack, in what I would call "main memory", same kind of memory as with Foo *a = new Foo; 否则,它将在堆栈中分配,即所谓的“主内存”,与Foo *a = new Foo;的内存类型相同Foo *a = new Foo; , but a different portion [ new uses heap memory, the stack is not same as heap, but same KIND of memory]. ,但使用不同的部分[ new使用堆内存,堆栈与堆不相同,而是相同的内存类型]。

Of course, if the class Foo contains a constructor, it could in itself call new and all manner of other functions that may or may not alter the usage of memory... 当然,如果类Foo包含构造函数,则它本身可以调用new各种形式的其他函数,这些函数可能会或可能不会更改内存的使用...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM