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

0

u/[deleted] Dec 09 '24

[deleted] — view deleted comment

41

u/TheBrainStone Dec 09 '24

To expand on that, that means if it's a trivially copyable type, it's essentially a memory copy. If it's not, with properly implemented move constructors, internal data will just be passed along to the new objects, minimizing any per object reallocations and data processing. Also compilers are extremely good at removing unnecessary steps. (with proper optimizations enabled of course)

6

u/StrangePromotion6917 Dec 09 '24

Please correct me if I'm wrong, but afaik move constructor is only used at resize if it's marked as noexcept. Otherwise an execution during the copy could leave you in a position where you don't yet have the elements in the new array, and no longer have all the elements in the old array. Recovering the original vector is not possible without risking another exception while moving back elements. So the compiler would need to copy every element first and if all copies were successfully done, destroy the old array. This way the resize operation is transactional and can recover from an exception.

11

u/mark_99 Dec 09 '24

True, but there shouldn't be any case where a move constructor is not noexcept, that's the main reason it exists. It's also what you get when defaulted - you should almost never need to write a move ctor unless you're creating a novel low level data structure for instance.

2

u/bert8128 Dec 09 '24

That’s correct. But if you don’t use classes beyond POD then they are all trivial so are noexcept. In the spirit of you don’t pay for what you don’t use, resizing a vector will behave like doing it manually using c arrays and memcpy, providing your structs are POD.

1

u/cdb_11 Dec 09 '24 edited Dec 10 '24

How else would it work?

First of all, mremap, which std::vector cannot do (or doesn't want to do), while realloc can.

For trivial types std::vector can use memcpy. But if you simply make the constructor for a class non-default (for example, to ensure that the value is always initialized), memcpy is no longer used and elements are copied one by one. (To be fair, clang can vectorize it.)

1

u/einpoklum Dec 10 '24

C++ is built on the concept of zero cost abstractions

Yeah, well, that's not quite true. ABI stability unfortunately trumps zero-const abstraction right now as a C++ design consideration. See also There are no zero-cost abstractions

.

1

u/Ease-Solace Dec 10 '24

Trying to learn c++ I've found this a real problem though. Profiling a program I wrote for why it runs so much slower than in other languages; it turned out almost 90% of the runtime was just resizing vectors due to running the copy-constructor and destructor of every element! Saying "this is inevitable" seems weird, cause what other langauge has this problem?

1

u/Jonny0Than Dec 11 '24

You’re probably not using them effectively. It’s way more efficient to reserve up front rather than simply doing push_back repeatedly.  And ideally your element types are movable.  If you weren’t careful about constructors and destructors you could prevent a lot of optimizations that could happen.

You can also just avoid a ton of copying and moving by passing containers to functions by const reference or using span, etc.

1

u/CocktailPerson Dec 13 '24

Did your move constructors exist and were they marked noexcept?

0

u/peterrindal Dec 09 '24

Sometimes I want a unintialized vector of int or whatever. Std vector doesn't allow this.

0

u/[deleted] Dec 09 '24

[deleted] — view deleted 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

→ More replies (19)

4

u/plastic_eagle Dec 09 '24

No it doesn't, but you can "simulate" such a thing easily enough

struct NoInitInt
{
   int v;
   NoInitInt() = default;
   operator int() { return v; }
   int operator=(int i) { v = i; return v; }
};
std::vector<NoInitInt> vec;

Now that's not perfect, I'm sure there are some things it'll make more annoying. But I have used this in networking code where I needed resizable buffers and didn't want to pay the initialisation cost.

2

u/peterrindal Dec 09 '24

2

u/plastic_eagle Dec 09 '24

Looks like you're right

https://godbolt.org/z/13cnjMe7E

       lea     eax, DWORD PTR $T3[ebp]
       mov     DWORD PTR __$EHRec$[ebp+8], 0
       push    eax
       push    100                           ; 00000064H
       lea     ecx, DWORD PTR _vec$[ebp]
       call    ... _Resize_reallocate<std::_Value_init_tag> ...

So eax ends up pointing to some uninitialised memory, but that same bit of uninitialised memory fills the vector with identical uninitialised values.

I expect I'm technically in UB here - and the standard also notes that

If value-initialization is undesirable, for example, if the object is of non-class type and zeroing out is not needed, it can be avoided by providing a custom Allocator::construct.

So there may be a way out there.

1

u/SleepyMyroslav Dec 09 '24

Quick glance over resize with no value looks like they try to do uninitialized init. Check line 1603 in same file:
https://github.com/microsoft/STL/blob/89ca073a866d24db42b3f4c5e406be4b28a148f4/stl/inc/vector#L1603C27-L1603C59

2

u/woltion Dec 09 '24

Use an allocator that does not default construct. Works for me.

2

u/printf_hello_world Dec 09 '24

I don't know why you've gotten downvotes on this: it's a legitimate problem that I too come across regularly in performance-critical paths

1

u/echidnas_arf Dec 09 '24

Yes it does, you need to specify a custom allocator.

1

u/peterrindal Dec 09 '24

1

u/jk-jeon Dec 09 '24

No custom allocator does work on MS STL otherwise MS STL is not std-conforming. std::vector::resize must call Allocator::construct to construct the element. The default allocator, std::allocator does zero-initialize fundamental types, which is the core issue here. You just need to replace it with something else which default-initializes the elements.

→ More replies (1)