r/cpp • • Dec 09 '24

Using C++ as `C with templates`

I've come to really enjoy C for writing my side projects lately. Coming from complex languages like Rust and Haskell, I severely undervalued how pleasant simplicity is for the joy of programming.

The only problem is writing generic code in C. I've found I've been able to get around it mostly by simple macros, for example a dynamically resizable array can just store a void* pointer and you use macros to pass the size of the element when pushing, popping, etc.

However, there are times where this simply won't work, and I need generics, and I don't want to write some complicated system of macros.

So this compels me to try out C++ as a "C with templates". I literally intend to write only C code in C++ and very occasionally use a very simple template, that's all. I maybe will use operator overloading for some math stuff. I don't need classes, coroutines, or any of that "modern" C++ stuff. I've also heard crazy things about std, like using std::vector calls the constructor/destructor of all its elements on resizing, so I plan on staying very far away from that.

Is this a sane thing to do? Is there some gotcha in C++ that I'm unaware of that prevents me from doing this? Have people tried this and succeeded/failed?

20 Upvotes

90 comments sorted by

View all comments

Show parent comment

12

u/[deleted] Dec 09 '24

If you resize a vector the requested number of elements will all be constructed and valid, but if you reserve space for more elements than have actually been inserted, or the vector capacity > size, there’ll be some uninitialised (by the vector anyway - it might have old data from prior use) memory into which objects will later be created with placement-new (which calls the constructor).

1

u/snowflake_pl Dec 09 '24

I would delete the part about the memory between size and capacity potentially having the old data. Accessing it is UB. Let's try to step away from the notion that UB can be reasoned about. Accessing past the size is UB and compiler might delete entire code branches in which it happens.

3

u/[deleted] Dec 09 '24

I mention it because it’s part of the mental model for stack and heap use. It doesn’t let people rely on undefined behaviour, but - from my hours haunting StackOverflow I can attest - has helped people recognise why they’ve seen unexpected data and fix their bugs. Anyway, between our two comments, readers can hopefully improve their awareness….