Below, I’m not declaring my_ints as a pointer. I don’t know where the memory will be allocated. Please educate me here!
#include <iostream> #include <vector> class FieldStorage { private: std::vector<int> my_ints; public: FieldStorage() { my_ints.push_back(1); my_ints.push_back(2); } void displayAll() { for (int i = 0; i < my_ints.size(); i++) { std::cout << my_ints[i] << std::endl; } } };
And in here, I’m declaring the field my_ints as a pointer:
#include <iostream> #include <vector> class FieldStorage { private: std::vector<int> *my_ints; public: FieldStorage() { my_ints = new std::vector<int>(); my_ints->push_back(1); my_ints->push_back(2); } void displayAll() { for (int i = 0; i < my_ints->size(); i++) { std::cout << (*my_ints)[i] << std::endl; } } ~FieldStorage() { delete my_ints; } };
main() function to test:
int main() { FieldStorage obj; obj.displayAll(); return 0; }
Both of them produces the same result. What’s the difference?
In terms of memory management, these two classes are virtually identical. Several other responders have suggested that there is a difference between the two in that one is allocating storage on the stack and other on the heap, but that’s not necessarily true, and even in the cases where it is true, it’s terribly misleading. In reality, all that’s different is where the metadata for the
vectoris allocated; the actual underlying storage in thevectoris allocated from the heap regardless.It’s a little bit tricky to see this because you’re using
std::vector, so the specific implementation details are hidden. But basically,std::vectoris implemented like this:As you can see, the
vectorclass itself only has a few members — capacity, size and a pointer to a dynamically allocated block of memory that will store the actual contents of the vector.In your example, the only difference is where the storage for those few fields comes from. In the first example, the storage is allocated from whatever storage you use for your containing class — if it is heap allocated, so too will be those few bits of the
vector. If your container is stack allocated, so too will be those few bits of thevector.In the second example, those bits of the
vectorare always heap allocated.In both examples, the actual meat of the
vector— the contents of it — are allocated from the heap, and you cannot change that.Everybody else has pointed out already that you have a memory leak in your second example, and that is also true. Make sure to delete the vector in the destructor of your container class.