다음 내용이 모두 사실입니까?
vector<Type> vect; //allocates vect on stack and each of the Type (using std::allocator) also will be on the stack
vector<Type> *vect = new vector<Type>; //allocates vect on heap and each of the Type will be allocated on stack
vector<Type*> vect; //vect will be on stack and Type* will be on heap.
어떻게 메모리는 내부적으로 할당 Type
A의 vector
또는 다른 STL 컨테이너?
답변
vector<Type> vect;
vector
스택에, 즉 헤더 정보 를 할당 하지만 비어있는 저장소의 요소 ( “힙”) 를 할당합니다 .
vector<Type> *vect = new vector<Type>;
무료 상점에 모든 것을 할당합니다.
vector<Type*> vect;
vector
스택에 스택과 프리 포인터에 많은 포인터를 할당 하지만이 포인트는 사용 방법에 따라 결정됩니다 (예 : 요소 0을 프리 저장소로, 요소 1을 스택으로 가리킬 수 있음).
답변
vector<Type> vect; //allocates vect on stack and each of the Type (using std::allocator) also will be on the stack
아니요, vect
스택에 있지만 항목을 저장하기 위해 내부적으로 사용하는 배열은 힙에 있습니다. 항목은 해당 배열에 상주합니다.
vector<Type> *vect = new vector<Type>; //allocates vect on heap and each of the Type will be allocated on stack
아니요. vector
클래스가 힙에 있다는 점을 제외하면 위와 동일 합니다.
vector<Type*> vect; //vect will be on stack and Type* will be on heap.
vect
스택에 있고 해당 항목 (포인터 Type
)이 힙에 있으며 Type
포인터가 가리키는 위치를 알 수 없습니다 . 스택에있을 수도 있고, 힙에있을 수도 있고, 전역 데이터에있을 수도 있고, 어디에도 없을 수도 있습니다 (예 :NULL
포인터).
BTW 구현은 실제로 스택에 일부 벡터 (일반적으로 작은 크기)를 완전히 저장할 수 있습니다. 그런 구현에 대해서는 아는 것이 없지만 가능합니다.
답변
실제로 스택과 힙이있는 구현 (표준 C ++은 그러한 것을 요구하지 않음)을 가정하면 유일한 유일한 진술은 마지막 진술입니다.
vector<Type> vect;
//allocates vect on stack and each of the Type (using std::allocator) also will be on the stack
마지막 부분을 제외하고는 마찬가지입니다 ( Type
스택에 있지 않음). 상상해보십시오.
void foo(vector<Type>& vec) {
// Can't be on stack - how would the stack "expand"
// to make the extra space required between main and foo?
vec.push_back(Type());
}
int main() {
vector<Type> bar;
foo(bar);
}
마찬가지로:
vector<Type> *vect = new vector<Type>; //allocates vect on heap and each of the Type will be allocated on stack
비슷한 카운터 예제를 사용하여 마지막 부분을 제외하고 True입니다.
void foo(vector<Type> *vec) {
// Can't be on stack - how would the stack "expand"
// to make the extra space required between main and foo?
vec->push_back(Type());
}
int main() {
vector<Type> *bar = new vector<Type>;
foo(bar);
}
에 대한:
vector<Type*> vect; //vect will be on stack and Type* will be on heap.
이것은 사실이지만 Type*
포인터가 힙에 있지만 포인터가 가리키는 Type
인스턴스는 다음과 같을 필요는 없습니다.
int main() {
vector<Type*> bar;
Type foo;
bar.push_back(&foo);
}
답변
이 진술 만이 사실입니다 :
vector <Type*> vect; //vect will be on stack and Type* will be on heap.
Type*
포인터의 양이 동적으로 변경 될 수 있으므로 포인터는 힙에 할당됩니다.
vect
이 경우 로컬 스택 변수로 정의했기 때문에 스택에 할당됩니다.
답변
벡터가 내부 보유 allocator
/ 메모리 할당에서 할당 해제의 책임이다 heap
를 들어 vector element
. 따라서 벡터를 생성하는 방법에 관계없이 벡터 element
는 항상에 할당됩니다 heap
. 벡터의 메타 데이터는 생성 방법에 따라 다릅니다.