0

What is the benefit of using smart pointers inside STL containers ( vectors, maps etc... ) knowing that these containers manages already the memory ?

Example:

std::vector<std::unique_ptr<int>>

instead of

std::vector<int*>
user2591935
  • 299
  • 1
  • 14

2 Answers2

5

If the objects are pointers it is not enough to manage the memory the pointers occupy. You also need to manage what the pointers point to. It is a good idea to store the objects pointed to instead of the pointers (in case of your example std::vector<int> would be appropriate), however, in case you have polymorphic objects that is not possible.

nwp
  • 9,623
  • 5
  • 38
  • 68
0

You can use it when you need to hold an array of references to objects. That way I can sort an array of references without actually moving the objects around in memory.

#include <algorithm>
#include <iostream>
#include <memory>
#include <vector>

int main()
{
        std::shared_ptr<int> foo(new int(3));
        std::shared_ptr<int> baz(new int(5));
        std::vector<std::shared_ptr<int> > bar;
        bar.push_back(baz);
        bar.push_back(foo);

        std::sort(bar.begin(), bar.end(), [](std::shared_ptr<int> a, std::shared_ptr<int> b)
        {
                return *a < *b;
        });

        for(int i = 0; i < bar.size(); ++i)
                std::cout << *bar[i] << std::endl;

        return 0;
}

Prints:

3
5
csnate
  • 1,601
  • 4
  • 19
  • 31
  • `shared_ptr`s [compare internal pointer values](http://en.cppreference.com/w/cpp/memory/shared_ptr/operator_cmp), not their content. – François Moisan Oct 22 '14 at 18:01