[英]C++ Allocating memory on the heap and stack?
Coming from a Java background, I'm still a little confused about allocating memory in C++.来自 Java 背景,我对在 C++ 中分配内存仍然有点困惑。 I'm pretty sure the first two statements are correct:
我很确定前两个陈述是正确的:
void method() {
Foo foo; // allocates foo on the stack, and the memory is freed
// when the method exits
}
void method2() {
Foo *foo = new Foo(); // allocates foo on the heap
delete foo; // frees the memory used by foo
}
But what about something like this?但是这样的事情呢?
void method3() {
Foo foo = *new Foo(); // allocates foo on the heap, and then copies it to the stack?
// when the method exits, the stack memory is freed, but the heap memory isn't?
}
Say I added foo
to a global array inside method3()
.假设我将
foo
添加到method3()
的全局数组。 If I tried to access one of foo
's data members after the method exits, would that work?如果我在方法退出后尝试访问
foo
的数据成员之一,那会起作用吗? And is method3()
prone to memory leaks?并且
method3()
容易发生内存泄漏吗?
Thanks in advance.提前致谢。
Foo foo();
Declares a function by the name foo
which returns a Foo
object and does not take any arguments.声明一个名为
foo
的函数,它返回一个Foo
对象并且不接受任何参数。 It is known as the most vexing parse in C++.它被称为 C++ 中最令人头疼的解析。 You probably meant:
你可能的意思是:
Foo foo;
It creates a foo
object locally/automatic storage.它在本地/自动存储中创建一个
foo
对象。 The object is automatically deallocated once the scope { }
in which it is declared ends.一旦声明它的范围
{ }
结束,该对象就会自动释放。
Foo *foo = new Foo(); // allocates foo on the heap
delete foo;
This is true, the object on freestore pointed by foo
is deallocated once you call delete
.这是真的,一旦您调用
delete
, foo
指向的 freestore 上的对象就会被释放。 There is no memory leak.没有内存泄漏。
Foo foo = *new Foo();
Allocates a Foo
object on freestore and then a copy of that object is used to initialize foo
.在 freestore 上分配一个
Foo
对象,然后使用该对象的副本来初始化foo
。 Since you do not have a pointer to the freestore allocated object, it causes a memory leak.由于您没有指向 freestore 分配对象的指针,因此会导致内存泄漏。 Note that if the destructor of
Foo
has some code which causes side effects then it is not merely memory leak but undefined behavior.请注意,如果
Foo
的析构函数有一些导致副作用的代码,那么它不仅仅是内存泄漏,而是未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.