【问题标题】:which is the best way to use dynamic array in C++ class?在 C++ 类中使用动态数组的最佳方法是什么?
【发布时间】: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 - 使用原始指针可能很好。它会通知该对象的所有权。

标签: c++ vector stl


【解决方案1】:

除非您一直按值复制组并且性能很关键,否则第二种方法可能是最好的。您将获得动态大小的向量,并且您不关心释放内存(向量按值存储)。同样在第二个和第三个变体中,您不需要存储大小,因为向量已经有了这些数据。

【讨论】:

  • 我的程序是时间关键的。我不知道第二种方式和第三种方式的性能差异。
【解决方案2】:

假设Group 拥有Person 的所有权,并且您想避免复制向量,您可以移动资源。

class Group {
    std::vector<Person> persons;
public:
    Group(std::vector<Person>&& ps) : persons(std::move(ps)) {}
};

Group 直接添加Person 而不暴露内部可能会更干净:

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
};

【讨论】:

    【解决方案3】:

    使用动态数组编程,首选选项是 std::vector(选项 2)。

    【讨论】:

      猜你喜欢
      • 2020-06-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-31
      • 2013-08-10
      • 2011-06-03
      • 1970-01-01
      • 2011-03-23
      • 2022-08-04
      相关资源
      最近更新 更多