-3

A C++ newer, please do not de-vote...

I have the class Group and Person, Group has many Persons. There are many ways to implement this. The following 3 ways are common.

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

I wonder that which one is the best way? is there any difference between the latter two ways? If using pointer, it's possible to have a memory leak.If using reference, we didn't need to consider leak problem, did it?

Alexia Wang
  • 121
  • 2
  • 11
  • 1
    Go with `std::vector` -- i.e approach 2 -- the extra level of indirection in approach 3 buys you nothing. – Alex Martelli Dec 24 '14 at 07:27
  • **never** user raw pinters in c++ except for compatibility with other code. **Always** use containers like `std::vector` – bolov Dec 24 '14 at 07:29
  • 1
    @bolov - Using raw pointers can be good. It informs the person on ownership of the object. – Ed Heal Dec 24 '14 at 07:56
  • See http://stackoverflow.com/questions/6675651/when-should-i-use-c-pointers-over-smart-pointers – Ed Heal Dec 24 '14 at 07:58

3 Answers3

2

Unless you copy groups by value all the time and the performance is critical, the second way is probably the best. You will get dynamic size vector, and you don't care about freeing memory (vector is stored by value). Also in second and third variant you don't need to store size because vector already has this data.

Dima Ogurtsov
  • 1,487
  • 1
  • 10
  • 18
1

Assuming Group has ownership of Person, and you want to avoid copy of the vector, you may move the resource.

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

And it may be even cleaner to add directly Person from Group without exposing internal:

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
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

Programming with dynamic arrays, preferred options is std::vector (option 2).