I’m a bit confused about the object references. Please check the examples below:
class ListHandler {
public:
ListHandler(vector<int> &list);
private:
vector<int> list;
}
ListHandler::ListHandler(vector<int> &list) {
this->list = list;
}
Because of the internal
vector<int> list;
definition, here I would be wasting memory right? So the right one would be:
class ListHandler {
public:
ListHandler(vector<int>* list);
private:
vector<int>* list;
}
ListHandler::ListHandler(vector<int>* list) {
this->list = list;
}
ListHandler::~ListHandler() {
delete list;
}
Basically all I want is to create a vector and pass to ListHandler. This vector will not be used anywhere else than the ListHandler itself so I’m expecting ListHandler to do all the other things and cleanup etc. stuff.
It depends on whether you want to share the underyling vector or not. In general, I think it is a good practice to avoid sharing wherever possible, since it removes the question of object ownership. Without sharing:
class ListHandler { public: ListHandler(const std::vector<int>& list) : _list(list) {} ~ListHandler(){} private: std::vector<int> _list; };Note that, unlike in your example, I make it
constsince the original will not be modified. If, however, we want to hang on to and share the same underlying object, then we could use something like this:class ListHandler { public: ListHandler(std::vector<int>& list) : _list(&list) {} ~ListHandler(){} private: std::vector<int>* _list; };Note that in this case, I choose to leave the caller as the owner of the object (so it is the caller’s responsiblity to ensure that the list is around for the lifetime of the list handler object and that the list is later deallocated). Your example, in which you take over the ownership is also a possibility:
class ListHandler { public: ListHandler(std::vector<int>* list) : _list(list) {} ListHandler(const ListHandler& o) : _list(new std::vector<int>(o._list)) {} ~ListHandler(){ delete _list; _list=0; } ListHandler& swap(ListHandler& o){ std::swap(_list,o._list); return *this; } ListHandler& operator=(const ListHandler& o){ ListHandler cpy(o); return swap(cpy); } private: std::vector<int>* _list; };While the above is certainly possible, I personally don’t like it… I find it confusing for an object that isn’t simply a smart pointer class to acquire ownership of a pointer to another object. If I were doing that, I would make it more explicit by wrapping the std::vector in a smart pointer container as in:
class ListHandler { public: ListHandler(const boost::shared_ptr< std::vector<int> >& list) : _list(list) {} ~ListHandler(){} private: boost::shared_ptr< std::vector<int> > _list; };I find the above much clearer in communicating the ownership. However, all these different ways of passing along the list are acceptable… just make sure users know who will own what.