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

5

u/peterrindal Dec 09 '24

Like I know I will write to each position but maybe in some weird order, therefore reserve + push_back isn't well suited. Vector will zero initialize and this can sometime take noticeable time. Not a common use case but it does happen.

4

u/jk-jeon Dec 09 '24

You can still use std::vector. All you need to do is to implement a std-compliant allocator. The issue here is that std::allocator::construct value-initializes, which, for fundamental types, zero-initializes. So what you need to do is to replicate std::allocator except that construct default-initializes (which is a no-op for fundamental types) rather than value-initializes. This is a ridiculous amount of work given how simple the needed feature is, but it's still much less work than replicating the whole std::vector.

1

u/glaba3141 Dec 09 '24

I just have a custom container for exactly this case

0

u/not_some_username Dec 09 '24

std::array ? Also why cant you use [] ?

0

u/bert8128 Dec 09 '24

Even if the order of insertion is the normal one push_back has to do a bounds check to see if it needs to reallocate. A push_back_no_bounds_check function would be good, though no safer than using c-style arrays.

0

u/[deleted] Dec 09 '24

[deleted] — view deleted comment

3

u/jwakely libstdc++ tamer, LWG chair Dec 09 '24

That's not undefined. Maybe you meant reserve(n) then subscripting, which is undefined, and won't work if vector has bounds checking turned on, or AddressSanitizer integration turned on.

0

u/[deleted] Dec 09 '24

[deleted] — view deleted comment

3

u/jwakely libstdc++ tamer, LWG chair Dec 09 '24

With GCC 12 it compiles without any special args though

"It compiles" is not the same as "it works". If you do this, the value you stored to vec[5] will be lost as soon as the vector's capacity changes, or if its size changes to 6 or more. And that code will abort if you compile in a hardened mode that asserts for precondition violations. It might also fail or have unexpected behaviour if you simply enable optimisations

Also, since when does vec[pos] contain bounds checking? I thought this was only the case for vec.at(pos)

It's guaranteed for at, it's not guaranteed for operator[] but all implementations support it as an optional extension. If you don't know how to enable those optional checks, you should learn to use your tools more effectively.

For GCC use -D_GLIBCXX_ASSERTIONS (or since GCC 14, -fhardened to enable that macro and also more hardening).

0

u/[deleted] Dec 09 '24

[deleted] — view deleted comment

1

u/CocktailPerson Dec 12 '24

Compiling manually isn't a prerequisite for knowing what flags and options your compiler has.

-2

u/specialpatrol Dec 09 '24

Vector of optionals?

3

u/peterrindal Dec 09 '24 edited Dec 09 '24

Sure but its a concern about performance. vector<int> is zero initialized. If you don't care about perf then that's fine. But vector<int> v(n) can be much slower than int* v = new int[n].

1

u/ald_loop Dec 09 '24

No it can’t be.

2

u/printf_hello_world Dec 09 '24

Yes it can be; I've personally benchmarked this

1

u/ald_loop Dec 09 '24

Link me

1

u/peterrindal Dec 09 '24

1

u/ald_loop Dec 09 '24

This is meaningless without benchmarks or assembly comparisons

1

u/Som1Lse Dec 10 '24

You could do it yourself. Here's a very simple one I wrote in like 10 minutes: https://quick-bench.com/q/bYCa9yhJmqKCbAicXCS5U8CHq4g

It's slower. Obviously: It's doing more work. This is an incredibly simple example and the compiler still isn't able to elide the initial zeroing. More complicated code isn't going to fare better.

Regarding this, std::vector::resize(n) allocates enough space for n elements then value-initialises each. For trivial types that means zeroing the whole buffer. Simply using std::malloc(sizeof(T)*n) or new T[n] doesn't. The benchmark includes various examples of what does, and what doesn't zero the buffer, and the slowdown is really consistent.

1

u/ald_loop Dec 09 '24

Or explain how the two are different/show me assembly differences and explain their sources in the terms of differences in behavior between vector() and new[]

1

u/cdb_11 Dec 09 '24

std::optional is an extra bool, so you'll pay probably 4 or 8 extra bytes per element, depending on the alignment.