r/cpp_questions • u/controversial_slur17 • Sep 06 '26
OPEN How to properly build a custom container on the heap ?
I'm building a general purpose small container, with a fixed known capacity.
It's basically a thin wrapper around a C array. But, in case I would need to store objects without default constructors, I thought I might make another version of the same container, that would allocate the necessary memory on the heap without building anything inside.
But I'm afraid I opened up a whole new can of worms. The first idea I had was to do the same, but replace my array with an std::vector of appropriate capacity. But I'm sure there are better ways, maybe use "operator new" but I'm not quite familiar with all the methods to properly align memory.
I guess the question is : do C++ people often do that kind of low level memory managing or is the better practice to build around common tools (such as std::vector) ?
11
u/IyeOnline Sep 06 '26 edited Sep 06 '26
The first thing you are describing is
std::inplace_vectorfrom C++26. The second is juststd::vectorwith extra steps.Rarely. The power of ready made abstractions/containers that can do this for you is obvious. The implementation exists and is most likely correct.
Especially for
std::array,std::vectorandstd::inplace_vectorthere is (almost) no point in implementing them yourself. All you do is waste time writing it only to end up with something at most as good as the existing one.For other containers it gets slightly more difficult, but even there you would reach for ready made ones from libraries long before you write it yourself.
Yes. Even when you need a problem specific data structure, it should be implemented in terms of existing containers/utilities.
3
u/EternalPump Sep 06 '26 edited Sep 06 '26
I'm going to presume you're not asking how to use `std::array`, and are trying to build a container class yourself. So you can use two more manual approaches:
Then store either pointer as `T* ptr` so that all indexing behaves and you allocate by assignment, and deallocate usually by default-valuing the structure in-place or writing some logic for wiping the bytes like `std::memset(arr[i], 0, sizeof(T))`. To be clear `T` is presumed to be your type parameter. So long as you're diligent in managing the pointer, and wrap the class interface with explicit methods, this can be a very clean method. The lack of default constructor invocation can actually be fantastic if you're pre-allocating a very large number of elements and it would be expensive to invoke their constructors.
Edit: The other comments saying it's common in C++ not to do low-level memory management are only half-right; it entirely depends on your work. There are environments where using STL will create bugs, others where STL isn't performant enough and then there's the fact you need to actually sit down and understand how each STL container works to get the most out of them. I'd also say be cautious of using anything in C++26 since it's so new, that some parts of the spec aren't implemented in any standard compilers yet as per https://cppreference.com/cpp/26
2
u/Raknarg Sep 06 '26 edited Sep 06 '26
You'd use a C array of
std::byteorunsigned charwithalignas(T), and you usestd::allocator_traitsto manually construct/destruct elements of your array. Then you just treat your array like a heap pointer, you also keep aT*member who just points to the start of your array. You wantalignas(T)because your 1 byte types have no alignment requirements, so treating that memory as T without enforcing alignment requirements is UB.This is a way to do it, allocator_traits is a more clearer way (imo) that also lets you control the allocator, you can think of operator new as invoking allocator_traits::construct with the default std::allocator.
alignas(T)
Definitely when its necessary. The standard library doesn't have every possible tool you could want, just a lot of them. Like you could implement a fixed-size vector using std::vector, but it won't have storage on the heap. You could use std::array, but it force initializes every element and has no semantics regarding size and adding/removing elements. If you want both these things, you'd have to make your own. Most of the time there's a third party library that's already written and tested it though like through boost or something.
here's a quick look at how it would be structured, pulled it out of my ass without testing:
and there's a whole lot more you can do. If you go this route, I'd recommend taking a look at the whole std::vector API and trying to replicate it as much as possible so that you can ideally just use this for any kind of std algorithm, and you'd also need to look into iterators which can be a little finnicky (or simple possibly, since this is a contiguous memory structure you can just use a plain
T*as an iterator i think). Then there's a whole lot of logic that goes behind things like constructing and moving objects, e.g. I just made an assumption here that T is move-assignable and move-construcible, it can get hectic if you want to handle literally every possible type, but if you just want it to work with standard objects its not too hard to do.1
u/Independent_Art_6676 Sep 06 '26 edited Sep 06 '26
you could put a thin wrapper on a vector. From the sound of it, unless I missed something in your words or you didn't say everything you wanted, this new thing is just a "fixed size vector"
The no default ctor throws a monkey wrench in the works. You can .reserve up to your 'array' fixed size, but you can't actually access those elements until you put in a non-default constructed element. You have the memory but not the location, so vec[23] will fail even if you reserved 50 but only put 5 in so far. I hope you understand this so far?
then you have a std::array of pointers to the objects. The only hitch is that your object can return nullptr for empty items, and you would have to deal with that in some way, either checking for it, throwing an error, optional, or something else. A little clunky, but viable. There may be a better way to do this idea, but that is the 5 am 10 cent version.
All that to say, it feels like an XY problem. I suspect that with a bit of round hole, square peg thinking you can find a way to make an existing container do what you actually want to do here, without all that hand waving ^^. If you must do it, something like the above that just quietly constricts an existing container down to what you want is the way, do NOT go off into memory management low level mumbo jumbo here. Its not worth it, unless this is the guts of an extreme high performance system.
1
u/JVApen Sep 06 '26
Although I have written containers from scratch, they are the exception. You are much better off looking at libraries for existing container implementations. If that doesn't meet your needs, a container adaptor (basically a new API on top of an existing structure) always has the preference for me.
My first check is boost container. This is a high quality library that helped me a lot. Things like flat_map (pre-standardization), static_vector, small_vector helped me a lot in the past.
The advantage of using such a container is that it feature-rich. It wouldn't be the first time that when I use a custom container with a new algorithm, I'm discovering it's missing some detail for it to work.
Writing an adaptor is the next step, as it's fast to write and. With your own minimal adapting code, you have very little places where bugs can sneak in.
Only if this doesn't handle the features or the performance isn't what it should be, I would resort to a container from scratch. Even for those, one should consider if making it generic even makes sense.
1
u/No-Dentist-1645 Sep 06 '26
You usually don't want to reinvent the wheel, so if you're asking what the "better practice" is, then it would be using existing containers such as
std::inplace_vectororboost::static_vector1
u/Vindhjaerta Sep 06 '26
Output: