Unique_ptr alternative for dynamically allocated array

I wrote a class that should interact with some old code, which requires several C-style arrays as arguments (or at least a pointer to the first element).

These arrays are members of my class and they are especially large (50kb), so I want to put them in a heap so that the objects of my class are not huge on the stack. I am a big proponent of using resource management objects, so I would rather not manage these arrays on the heap.

I found that using unique_ptr for this works especially well. For instance:

std::unique_ptr<SOMETYPE[]> someArrayName

and using:

someArrayName(new SOMETYPE[someLargeSize])

in the initialization list of my constructor. This allows me to use them like regular C arrays, using the .get() method for functions that need this as arguments, and I don't need to manage the memory myself. But I just realized that my colleague (the one who really compiles our code for releases) is still on VS2008, clearly not having support for C ++ 0x functions like unique_ptr . Firstly, is this my current solution using unique_ptr for this good one? If so, is there a replacement for this to support all the behavior I need, something like boost?

+4
source share
1 answer

Using std::unique_ptr will require highlighting with new[] . Which is never (or almost never) the best solution. Use only std::vector . In pre-C ++ 11, go &array[0], array.size() ; in C ++ 11 you can be more clear and go through array.data(), array.size() . (This also has the advantage that you do not need special random empty vectors.)

+5
source

Source: https://habr.com/ru/post/1493483/


All Articles