我有班级组和人,组有很多人。有很多方法可以实现这一点。以下3种方式很常见。
// 1. using dynamic pointer.
class Group {
Person *persons;
int size;
public:
Group(Person *ps, int sz);
};
// 2. using STL container.
class Group {
vector<Person> persons;
int size;
public:
Group(vector<Person> ps, int sz);
};
// 3. also STL container, but using pointer.
class Group {
vector<Person> *persons;
int size;
public:
Group(vector<Person> *ps, int sz);
};
我想知道哪一个是最好的方式?后两种方式有什么区别吗? 如果使用指针,可能会有内存泄漏。如果使用引用,我们不需要考虑泄漏问题,是吗?
答案 0 :(得分:2)
除非您一直按值复制组并且性能至关重要,否则第二种方式可能是最好的。您将获得动态大小向量,并且您不关心释放内存(向量按值存储)。同样在第二和第三个变体中,您不需要存储大小,因为向量已经包含此数据。
答案 1 :(得分:1)
假设Group
拥有Person
的所有权,并且您想避免复制该向量,则可以移动该资源。
class Group {
std::vector<Person> persons;
public:
Group(std::vector<Person>&& ps) : persons(std::move(ps)) {}
};
从Person
直接添加Group
而不暴露内部可能更清晰:
class Group {
std::vector<Person> persons;
public:
#if 1
// generic method,
template <typename ... Args>
Person& AddPerson(Args&&... args) {
persons.emplace_back(std::forward<Args>(args)...);
return persons.back();
}
#else
// but it would be simpler to just use directly
// the arguments of Person's constructor
Person& AddPerson(const std::string& name) {
persons.emplace_back(name);
return persons.back();
}
#endif
};
答案 2 :(得分:0)
使用动态数组编程,首选选项是std :: vector(选项2)。