Managing Containers of Pointers

Hey all,

Would you recommend managing containers of pointers through unique_ptr<T> interfaces? In an effort to keep memory management errors to a minimum, I want to create a container of pointers that will automatically clean themselves up after the container's destructor is called. Is that what this code is doing?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
#include <memory>

struct myStruct
{
	myStruct(int i) { myData = i;}
	int myData;
};

int main()
{
	{ // Block Scope
		std::vector<std::unique_ptr<myStruct>> myContainer; //container created

		for(int i = 0; i < 10; i++)
		{
			myContainer.push_back(std::unique_ptr<myStruct>(new myStruct(i))); // This allocates a new struct on freestore and passes ownership to a unique_ptr?
		}
	} // container destroyed

	// all of myStructs released?
   return 0;
}
Last edited on
Yes, the pointers will be freed when myContainer goes of out scope.

Note that you also have std::make_unique_ptr().
Thank you! This is helpful. I didn't know about std::make_unique_ptr().
Topic archived. No new replies allowed.