[英]Could be an object created on the heap treated as 'being on stack' in C++?
Have the code: 有代码:
struct FooBar
{
FooBar()
{
MyObject obj;
/// when c-tor is ended, obj must be deleted through d-tor call
}
};
...
FooBar* fooBar(new FooBar);
fooBar
is allocated on the heap. fooBar
在堆上分配。 But object MyObject obj
inside FooBar
's constructor does not know where it is created. 但是
FooBar
的构造函数中的对象MyObject obj
不知道它的创建位置。 So could be MyObject
instantiation in the context of FooBar
treated like it was created in the stack? 那么在
FooBar
上下文中MyObject
实例化可以像在堆栈中创建的FooBar
对待吗?
Does object allocated on the heap have its own stack? 分配在堆上的对象是否具有自己的堆栈? What is the size of such stack?
这种堆栈的大小是多少?
obj
is allocated on the stack in your example (the "ordinary" stack, the "same" that is used in the code that calls new FooBar
- assuming your environment has a stack to begin with). obj
在示例中分配在堆栈上(“普通”堆栈,在调用new FooBar
的代码中使用的“相同”-假定您的环境有一个堆栈开始)。
The fact that this
points to somewhere on the heap doesn't change the fact that the constructor is a (relatively) ordinary function call, and uses the same stack as other functions. this
指向堆上某处的事实并不会改变构造函数是(相对)普通函数调用的事实,并且使用与其他函数相同的堆栈。
C++ does not know about stack or heap. C ++不了解堆栈或堆。 It does know about objects with automatic and dynamic storage duration.
它确实知道具有自动和动态存储持续时间的对象。 In your case,
fooBar
has dynamic storage duration (because it is created using new
). 在您的情况下,
fooBar
具有动态存储持续时间(因为它是使用new
创建的)。 It will live until you call delete
on it. 它会一直存在,直到您对其调用
delete
。 obj
has automatic storage duration (because it is not created using new
). obj
具有自动存储期限(因为它不是使用new
创建的)。 Its lifetime ends when the enclosing function (the FooBar
-constructor) ends. 当封闭函数(
FooBar
)结束时,其生存期结束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.