0

Sorry for the headline I wasn't sure how to correctly express my problem. I have a class that does generate an array based on a certain algorithm. The array length may vary so I'd like to allocate the array dynamically. The caller - of course - wants to access this array using a getter where I return the reference to the array. My question:

Is there a rule or a good practice if I either let the user allocate / de-allocate the resource and just let him pass the resource to my class and act on this or will I take care of the allocation / de-allocation (RAII) in order to prevent memory leaks?

Any help is appreciated!

binaryguy
  • 1,167
  • 3
  • 12
  • 29
  • 6
    Using a `std::vector` lifts all worries. – 101010 Dec 03 '15 at 22:18
  • I agree with @101010 why do u feel you need to use an array? – Youssef Bouhjira Dec 03 '15 at 22:19
  • @101010 `vector` is a form of having the function do the allocation. The function will be unusable by someone who doesn't want to use a vector (or wants to use a vector with a non-standard allocator) . – M.M Dec 03 '15 at 22:27
  • 1
    Do use the vector if possible. If the class generates the data and then doesn't care about it, return the vector and let copy elision or std::move deal with the copying costs. If the class generates the data and then has some skin in the game, consider having the class maintain total ownership. Don't let the user touch the data store. Don't give them a reference to the whole thing. Have the class implement `operator[]` and provide iterators so the user can use the class as though it was the array. – user4581301 Dec 03 '15 at 22:29
  • @M.M The OP says "I have a class that does generate an array based on a certain algorithm." (i.e., the class object is the owner), where does custom allocator fits in? – 101010 Dec 03 '15 at 22:34
  • @101010 when OP says "I either let the user allocate / de-allocate the resource " I assume is is talking about the caller who will access the array. If the class is managing memory for the array then that line doesn't make sense. – M.M Dec 03 '15 at 22:37
  • @M.M I must admit you're correct, as well that I didn't read the last paragraph :). – 101010 Dec 03 '15 at 22:43
  • I thought about using a std::vector but the algorithm involves a lot of reordering and removing. So I decided to go with a simple array... – binaryguy Dec 03 '15 at 23:15
  • @user4581301 I guess that is the right answer for me. I don't have the opportunity to use a std:vector (see answer before) so I'd prefer using an internal array. And I actually don't want anyone to touch my data so I need to ensure that it does not get exposed to the actual user in a way the he can alter it. So I guess I go with some kind of iterator approach. Thank you. – binaryguy Dec 04 '15 at 01:22

0 Answers0