我实际上是C ++的初学者,我正在尝试学习以专业的方式使用C ++。现在,我编写了一个程序,以获取有限数量的员工规格,包括姓名,年龄,薪水,甚至为用户提供晋升所需人员的能力。我定义了一个类,有人建议我使用向量。现在,我认为有什么办法可以使用智能指针了吗?我的意思是一种管理内存并提高程序速度的方法吗?
谢谢。
[如果您使用智能指针,最好是选择std::shared_ptr
,以避免在插入或重新分配时出现复制问题,或者如果需要唯一成员身份,则将std::move()
与unique_ptr
一起使用,如下所示(并考虑Eljay的评论) )
#include <iostream>
#include <vector>
#include <memory>
int main()
{
std::unique_ptr p = std::make_unique<Foo>(Foo{arg1, ...});
std::vector<std::unique_ptr<int>> vec(2);
vec[0] = std::make_unique<Foo>(Foo{arg1, ...});
vec[1] = std::make_unique<Foo>(Foo{arg1, ...});
vec.insert(vec.cbegin(), std::move(p));
}
OR
#include <iostream>
#include <vector>
#include <memory>
int main()
{
std::shared_ptr p = std::make_shared<Foo>(Foo{arg1, ...});
std::vector<std::shared_ptr<int>> vec(2);
vec[0] = std::make_shared<Foo>(Foo{arg1, ...});
vec[1] = std::make_shared<Foo>(Foo{arg1, ...});
vec.insert(vec.cbegin(), p);
}