Reputation: 63
I'm a C++ newbie and I am working on university project Driver Book in C++. I am using vector for the first time and I would like to make it work with dynamic memory allocation.
I have vector declared like this:
vector <item> book;
What is needed to make it work with dynamic memory allocation?
Thanks in advance.
Upvotes: 1
Views: 16152
Reputation: 1
This question thread has useful, relevant information on memory allocation for std::vector. Here's a summary:
std::vector<Type> foo{}; // Allocates the vector(i.e. the header info) on the stack, elements on the heap.
std::vector<Type> *foo = new std::vector<Type>{}; // Allocates everything on the heap, except the foo pointer which is on the stack.
std::vector<Type*> foo{}; // Allocates the std::vector on the stack, and a bunch of pointers on the heap. Where they point is determined by use.
So, to build on other answers, the elements of std::vector are already dynamically allocated.
Upvotes: 0
Reputation: 133
I want to point out that when others say "vector already internally dynamically allocates when you push_back into it", it means that objects pushed into the vector are dynamically allocated, not the vector itself is automatically dynamically allocated upon creation.
For example, if you want a vector created inside a function to persist, below code will lead to undefined behavior because the vector itself is not automatically dynamically allocated. After the return, the vector's memory location will automatically be cleaned up. The reference will be referencing garbage.
#include <iostream>
#include <vector>
using namespace std;
vector<int>& f() {
vector<int> v = vector<int>({4, 5, 6});
return v;
}
int main() {
vector<int>& b = f();
std::cout << "Hello World!\n";
}
If you hope to keep the vector in existence even as the function returns, you still need to use dynamically allocated memory.
#include <iostream>
#include <vector>
struct Node {
int a;
Node(int a) : a(a) {}
};
using namespace std;
vector<int>& f() {
vector<int>& v = *new vector<int>({4, 5, 6});
return v;
}
int main() {
vector<int>& b = f();
vector<int>* bptr = &b;
cout<<b[2]<<endl;
delete bptr;
std::cout << "Hello World!\n";
}
Upvotes: 0
Reputation: 3379
To eleborate a bit more: vector<T>
is a resizable array, which can hold objects of type T
.
It internally get memory dynamically. Now if you want to create the vector with dynamic allocation you are always free to use vector<item>* myVec = new vector<item>();
Although generally you'll never need to create a vector
dynamically.
Upvotes: 6
Reputation: 227370
The vector uses dynamic memory allocation internally. So all you need to do is put elements in it:
item i = ....;
book.push_back(i);
See this reference for more things you can do with a vector.
Upvotes: 2
Reputation: 28168
Done. vector
already internally dynamically allocates when you push_back
into it.
Upvotes: 5