std::vector<object*> objects;
Object* o = new Object();
objects.push_back(o);
我想訪問objects[0]. 那么,當我訪問它時,是否有指向堆疊的指標,然后是堆?或者,這是如何作業的?
uj5u.com熱心網友回復:
這里有一些東西要解壓。
首先,假設你有一個vector<object*>你所說的,并且它被宣告為自動存盤持續時間。
void f()
{
// declared with automatic storage duration "on the stack"
std::vector<object*> my_objects;
}
向量本質上存盤一個連續的記憶體塊,它本質上是一個可以存盤的n 個物件的陣列,在我們的示例中,向量可以包含0..n object*,并且實作將通過具有指向第一個元素的指標來做到這一點,并且該連續的記憶體塊存盤在“堆上”。
void f()
{
// declared with automatic storage duration "on the stack"
std::vector<object*> my_objects;
// now, my_objects holds 10 object*, and the storage for them
// is allocated "on the heap"
my_objects.resize(10);
}
這很有趣,因為當我們存盤時,object*我們不知道它是否是在堆上分配的。舉個例子:
void f()
{
// declared with automatic storage duration "on the stack"
std::vector<object*> my_objects;
// now, my_objects holds 2 object*, and the storage for them
// is allocated "on the heap"
my_objects.resize(2);
auto dyn_obj = std::make_unique<object>();
object auto_obj;
my_objects[0] = dyn_obj.get();
my_objects[1] = &auto_obj;
}
上面,我們有一種情況,存盤 my_objects.data()是在堆上分配的,被object指向的my_objects[0]被分配在堆上,而被object指向的my_objects[1] 不是。
如您的示例所示:
std::vector<object*> my_objects; // automatic storage duration
object* o = new object; // o has automatic storage duration
// while what it points to is "on the heap"
my_objects.push_back(o); // an allocation will happen
// because my_objects has to
// allocate storage to hold o
my_objects是“在堆疊上”,就像o. 當包含這些東西的范圍退出時,它們將被“銷毀”。 my_objects將運行它的解構式,而o將“消失”。
呼叫my_objects.push_back()將“在堆上”分配記憶體以保存1 * sizeof(object*)(至少),并將值復制o到該存盤空間中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/506507.html
