I'm wondering what is the advantage of using a vector of pointers in the following example. Are there any differences between these three vectors in terms of memory management? Which one is most efficient?
class foo{
public:
foo(int a);
private:
int x;
};
foo::foo(int a){
}
int main() {
std::vector< std::shared_ptr<foo> > vec =
{std::make_shared<foo>(2), std::make_shared<foo>(2)};
std::vector<foo*> vec2 = {new foo(2), new foo(2)};
foo o1(2), o2(2);
std::vector<foo> vec3 = {o1, o2};
return 0;
}
Based on your current example, I would say that the std::vector<foo>
is your best option.
std::vector< std::shared_ptr<foo> > vec =
{std::make_shared<foo>(2), std::make_shared<foo>(2)};
Using the shared_ptr will take care of memory management by storing a reference count. When there are no more references to the object, the object will be destroyed.
std::vector<foo*> vec2 = {new foo(2), new foo(2)};
foo o1(2), o2(2);
std::vector<foo> vec3 = {o1, o2};
Normal ints and pointers are the same size so with one int in your foo class, the only difference is the possibility of memory leaks if you forget to delete the pointer.
Deleting a pointer can also create exceptions if another pointer is using the foo object and tries to use it.
If you require pointers, smart pointers are normally the best option because of their memory management.