简体   繁体   English

C ++在STL容器中使用智能指针

[英]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 ? 知道这些容器已经在管理内存,在STL容器(向量,映射等)中使用智能指针有什么好处?

Example: 例:

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

instead of 代替

std::vector<int*>

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. 一个好主意是存储指向的对象而不是指针(在您的示例std::vector<int>合适的情况下),但是,如果您有不可能使用的多态对象。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM