在STL容器(向量、映射等)中使用智能指针有什么好处?)知道这些容器已经管理内存了吗?
示例:
std::vector<std::unique_ptr<int>>而不是
std::vector<int*>发布于 2014-10-22 17:45:03
如果对象是指针,则不足以管理指针占用的内存。您还需要管理指针指向的内容。但是,最好是存储指向的对象,而不是指针(在您的例子中,std::vector<int>是合适的),如果您有多态对象是不可能的。
发布于 2014-10-22 17:55:33
当您需要保存对对象的引用数组时,可以使用它。这样,我就可以对引用数组进行排序,而不必实际移动内存中的对象。
#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
5https://stackoverflow.com/questions/26513680
复制相似问题