【发布时间】:2023-03-08 14:29:01
【问题描述】:
C++ 较新,请不要投票...
我有 Group 和 Person 类,Group 有很多 Person。有很多方法可以实现这一点。以下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);
};
我想知道哪个是最好的方法?后两种方式有什么区别吗? 如果使用指针,可能会发生内存泄漏。如果使用引用,我们不需要考虑泄漏问题,是吗?
【问题讨论】:
-
使用
std::vector-- 即方法 2 -- 方法 3 中的额外间接级别对您没有任何好处。 -
从不在 c++ 中使用原始 pinters,但与其他代码的兼容性除外。 始终使用
std::vector之类的容器 -
@bolov - 使用原始指针可能很好。它会通知该对象的所有权。