user2591935
user2591935

Reputation: 299

C++ Use of smart pointers inside STL containers

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*>

Upvotes: 0

Views: 1256

Answers (2)

csnate
csnate

Reputation: 1641

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

Upvotes: 0

nwp
nwp

Reputation: 9991

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.

Upvotes: 5

Related Questions