1

I have a scenario where I want to store a number of objects of a particular class(dummy) type in a vector.

vector<Dummy> dummyObjects;

My collection may end up containing >5k objects. Now, this vector needs to be accessed by another class (Dummy_2). The class Dummy_2 is just for display. So, my doubt was whether I should return a pointer to this vector to Dummy_2 or should I just return the vector object which will as we know create a copy of this vector? If we return a pointer to this vector, do I need to worry about de-allocating the memory later once my program ends or would one of the smart pointer would help me to overcome this de-allocating of the memory?

Siddhant
  • 571
  • 1
  • 8
  • 32
  • If `Dummy` is a type, `*Dummy` is not valid. Why would you dereference a type? – Rakete1111 Jul 01 '17 at 08:13
  • Yes, I had this doubt. Should I store the instance of Dummy type in the vector or should I store a pointer to the Dummy type instance in the vector? – Siddhant Jul 01 '17 at 08:15
  • It really depends on your use case though IMO. We can't give you all scenarios because there are too many, and so your question is I think too broad. – Rakete1111 Jul 01 '17 at 08:17
  • Depends entirely on `Dummy`. Are you sure `std::vector` wouldn't work? – Christian Hackl Jul 01 '17 at 08:18
  • The pain of freeing up allocated memory is only there because you allocated it in the first place, which is *very likely* not necessary. It isn't in most circumstances. I would not be surprised if `std::vector` was all that is required for whatever you're doing. But as-presented, this question is too broad. – WhozCraig Jul 01 '17 at 08:19
  • Let me re-phrase the question. – Siddhant Jul 01 '17 at 08:24
  • @Siddhant Use a pointer or even better a const reference. No, you don't need to worry about memory deallocation in those cases. – HolyBlackCat Jul 01 '17 at 08:45
  • 5000k doesn't sound like a lot, really. Naturally, it depends on how often you will pass that vector around. Is it in a tight loop? Or does it occur just once every few minutes? I'd say just return a copy and be done with it until you experience *measurable* performance problems. Don't waste time and energy with complex pointer solutions that turn out to be unnecessary. And of course, thanks to move semantics, chances are that little copying will actually occur behind the scenes. – Christian Hackl Jul 01 '17 at 08:48
  • It will occur once every few minutes. – Siddhant Jul 01 '17 at 08:54
  • @Siddhant if you're able to do with with pointers/references, do it this way. If not, copy *should* be good enough, even though it's a waste of performance. – HolyBlackCat Jul 01 '17 at 09:02

0 Answers0