[英]C++ Use of smart pointers inside STL containers
知道這些容器已經在管理內存,在STL容器(向量,映射等)中使用智能指針有什么好處?
例:
std::vector<std::unique_ptr<int>>
代替
std::vector<int*>
如果對象是指針,則不足以管理指針占用的內存。 您還需要管理指針指向的內容。 一個好主意是存儲指向的對象而不是指針(在您的示例std::vector<int>
合適的情況下),但是,如果您有不可能使用的多態對象。
當您需要保存對對象的引用數組時,可以使用它。 這樣,我可以對引用數組進行排序,而無需實際在內存中移動對象。
#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;
}
打印:
3
5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.