r/cpp • • Mar 27 '21

Not so modern c++

https://www.polymonster.co.uk/blog/not-so-modern-cpp
0 Upvotes

66 comments sorted by

11

u/Wouter-van-Ooijen Mar 28 '21

Quote "I always found enum handling to be a poor area in c++ I hoped enum_class would sort me out but I preferred my older school alternative because it can be used as an int or as bit-mask as well."

OTOH enum class is a strong type, so if you use enums as unique values (not as bit fields) it protects you from accidentally passing a value of a different enum. IMO well worthwile in such a case.

When you use enums as bitfields as you propose you essentially loose all type information. My preference for that use case would be to use serparate types, with values that can be bit-operated (&, |, ^, ~ ) but not value-operated (+, -, *, %, etc). Not difficult to make, with zero run-time overhead.

2

u/__shufb Mar 28 '21

Yeah good suggestion, I hadn’t thought about making a type which only allows the bit wise ops, certainly something I will take a look at.

6

u/Wouter-van-Ooijen Mar 28 '21

" only allows the bit wise ops "

When I am in a mood to stirr a discussion I say that IMO

- signed integers should have arithemetic operations, but no bit-wise operations

- unsigned integers should have bit-wise operations, but no artithmetic operations

For values that describe bits (probably in a hardware register) I would like to go one step further: the values that are relevant to a particular register should allow bit-wise operations among themselves, but not with values relevant to other types of registers. (Things can get interesting to get right when different types of registers share bitfields.)

1

u/__shufb Mar 28 '21

Interesting, although I’m not entirely sure exactly what you mean. Given a 64 bit unsigned int used as bit mask in a 64 bit architecture which registers can it be used with which share bit fields?

4

u/Wouter-van-Ooijen Mar 28 '21

I was talking special-purpose hardware registers (memory-mapped peripherals), which you will encounter (only) in embedded systems or device-driver level programming. Not CPU registers.

1

u/__shufb Mar 28 '21

Thanks, It’s not really an area I am that familiar with myself but it’s good to know about.

I’m glad you picked out something else to discuss other than c vs c++ performance like a lot of others in this thread :)

4

u/Wouter-van-Ooijen Mar 29 '21

I’m glad you picked out something else to discuss other than c vs c++ performance like a lot of others in this thread :)

For me, that one has been decided a long time ago and hence not very interesting. For practical purposes (OK, give or take a few edge cases), C is a subset of C++, so C can never be faster than C++.

What remains (and what is still interesting) is preformance differences between various C++ styles.

1

u/jk-jeon Mar 29 '21

Eh, I disagree. In my ideal world, I want to have all of the following four separately, with reasonable rules for converting between them:

- signed integers: approximation of mathematical integers, with a prescribed precision limit. Hence, all arithmetic operations should be supported, with undefined behaviors when overflow/underflow occurs. Order relations (<, >, <=, and >=) should be supported as well. Bitwise operations don't make sense.

- unsigned integers: approximation of mathematical nonnegative integers, with a prescribed precision limit. Hence, all arithmetic operations except subtraction should be supported, with undefined behavior when overflow occurs. Subtraction is also supported if the result doesn't underflow, otherwise the behavior is undefined. Order relations should be supported as well. Bitwise operations don't make sense.

- integers modulo 2^N: precisely what the name describes. Hence, all arithmetic operations except division should be supported with no undefined behavior. Since computing the modular inverse is not a trivial task, not supporting division at all makes sense. Some people can argue that order relations and bitwise operations might make sense to some extent, but I'd say they should not be supported.

- Bitsets: precisely what the name describes. Hence, neither arithmetic operations nor order relations make sense while bitwise operations do make perfect sense. In fact, mathematically speaking, + and - should mean XOR and * should mean AND so arithmetic operations except division actually do make sense, but it should be wiser to just stick to ~, &, |, and ^. Bit-shifts are defined only for bitsets.

Also, things like arithmetic operations/order relations between signed and unsigned integers and multiplication of integers modulo 2^N by signed/unsigned integers should be supported as well.

However, I'd admit that whether it is beneficial to have separate types for unsigned integers (which are not integers modulo 2^N nor bitsets) is debatable.

2

u/Wouter-van-Ooijen Mar 29 '21 edited Mar 29 '21

I think I agree with you in principle, and we agree that types with both arithmetic and logical operations are not a good idea. (I think I mildly disagree about + for bitwise OR, but that might be engrained habit.)

But in C and C++ we have only signed and unsigined integers, not the 4 categories that you mention. So what you describe is a new language, what I describe is how I would use the current language(s), with only signed and unsigend. So for your categories:

  • signed -> no doubt, use signed integers. A pity they support bit operations.

  • unsigend with UB overflow/underflow -> not available in C and C++, use signed when performance matters more, use unsigned when the extra range matters.

  • modulo -> no doubt, use unsigned integers. A pity they support bit operations.

  • bit sets -> no doubt, use unsigned integers. A pity they support value arithmetic.

Your 2nd category, unsigned integers, is the IMO the most problemamtic, because the C++ mapping has not only unwanted operators, but also unwanted behaviour (guaranteed modulo artithmetic), which can cause a performance hit.

For the 2nd category I use signed, but recently I think that should maybe be unsigned for compile-time calculations. But what to choose for functions that can be run at compile time AND run time...

1

u/jk-jeon Mar 29 '21

Yeah, I probably misread your previous comment :) And I should have said "my ideal world that will never come" anyway lol

Of course I agree with all of your points. It is sad that unsigned integers are not really unsigned integers but rather mysterious mixture of completely different things, resulting in suboptimal performance and other pitfalls for no good reason.

By the way, I didn't say + means OR; I said it should mean XOR. Or, are you claiming that it should mean OR rather than XOR? To my view, it is far more natural to think + as XOR, because in that case, together with thinking * as AND, we can do all of usual arithmetic just like ordinary numbers, without any subtlety at all (but with some peculiarity of course). On the other hand, if you want to treat + as OR, you must give up convenient computational rules like a+b=a+c implies b=c, and replace those with counterintuitive nonsenses like a+bc=(a+b)(a+c).

1

u/Wouter-van-Ooijen Mar 29 '21 edited Mar 29 '21

:)

I never gave + meaning XOR versus OR much thought, I didn't read your post long enouigh and thought yoy meant + == OR. But either way, | == OR is so ingrained in my brain that I can't look at alternatives without prejudice.

BTW if * is AND (I agree) and + (and -?) is XOR (I might agree), is there an obvious symbol for (inclusive) OR?

1

u/jk-jeon Mar 29 '21

Um, sorry I didn't get your question. Is there an obvious symbol for what?

(BTW, if we are happy to think + as XOR, then + and - have no difference at all, because a XOR a is always zero for all a. So, a is equal to its additive inverse, which means adding a and subtracting a are just same.)

1

u/Wouter-van-Ooijen Mar 29 '21

(edited) OR

1

u/jk-jeon Mar 29 '21

Even if we were to accept this abstract nonsense (about treating + as XOR), still | seems like the best choice for OR.

1

u/Dean_Roddey Mar 28 '21

You can make class type enums very powerful with a little tooling. I have strong enumeration support built into my IDL generator, and it makes them into what they could be.

https://www.codeproject.com/Articles/1275506/Making-Cplusplus-enumerations-first-class-citizens

It supports contiguous, non-contiguous and bitmapped types. Depending on type it provides inc/dec, bitwise operators, translation between name and value, between ordinal and value, and between an alternate numeric value and value, translation to two other optional text values which can be loadable text, validity checking, binary streaming support, and text streaming support (you indicate which of the text values you want used.)

And my indexable collection classes allow you to indicate an index type, which defaults to an unsigned 32 bit but you can set it to an enum to tie the collection to an enum for indexing, which can be very useful, and there's no casting involved.

So they can be quite powerful, they just aren't for most folks.

2

u/Wouter-van-Ooijen Mar 28 '21

I try to avoid anything outside C++ (including code generators) as much as possible, so no thanks. But could be usefull for others.

1

u/Dean_Roddey Mar 28 '21

You are a code generator, so better stop now. And there's absolutely nothing that's outside of C++ of course, it's all completely legal code you could have written by hand, it just saves you a vast amount of hassle and insures it's all correct.

In my case the primary use of the IDL generator is to generate code for the ORB (remote interfaces.) But it also does the advanced enum stuff.

4

u/Wouter-van-Ooijen Mar 29 '21

My (pactical) objection is that there is now source (the input to your generator) that is not C++, and a tool to maintain. For me that is something to avoid if possible. That doesn't mean I never use it, but only when I deem it worth the costs.

1

u/Full-Spectral Mar 29 '21

I can't see how anyone would ever consider it not worth it. It makes enums into what they should be, which is a quite powerful tool. I'm not saying use mine, which you couldn't unless you used my own system. But it's pretty easy to build one, and it's trivial to incorporate into any reasonable sort of build system so that it's all auto-magical.

2

u/Wouter-van-Ooijen Mar 29 '21

Some questions:

  • How do you handle enum values that depend on the context (for instance C++ template parameters, or constexpr calculations)?

  • What is the code size overhead?

1

u/Full-Spectral Mar 29 '21 edited Mar 29 '21

I'm not sure exactly what you mean on the first one. I can't think of anything about those scenarios that would make any difference. At the heart of it it's still just a regular enum class declaration, the same as you'd write by hand.

On the second, it's not much at all. Basically it generates a table, and some small calls that access that table. It's not enough to worry at all about, IMO, given the benefits.

I actually also did a small, standalone one, which is in the repo below. You could adapt it to your needs to do no more than what you want. It's not quite as powerful as the one in my IDL generator, since that one can lean on some known functionality in my overall system.

https://github.com/DeanRoddey/CQEnum

1

u/Wouter-van-Ooijen Mar 29 '21

It's not enough to worry at all about, IMO, given the benefits.

Anything more than 0 bytes overhead is something to wory about if your falsh size is a few Kb.

1

u/Full-Spectral Mar 29 '21

Ok, yes, if you are at the extreme lower end of the memory spectrum, it could matter. For anything else, it would be between minimal and negative concern.

→ More replies (0)

1

u/Wouter-van-Ooijen Mar 29 '21

I'm not sure exactly what you mean on the first one.

Something like

contexpr int f( int n ){ ... }

template< int N >
struct {
   enum class x = { a = N, b = f( N ) }
   ... more code
};

1

u/Full-Spectral Mar 29 '21

You couldn't use it for that of course, not with the little one above anyway, since it would have no way to reference that function. That could be added of course if you wanted. The 'value' of that enum value would just need to be able to be entered as "f(N)", which would get generated literally as that into the enum declaration.

→ More replies (0)

32

u/delarhi Mar 27 '21

TL;DR: OP prefers optimization over semantics so more or less writes C.

-14

u/qoning Mar 27 '21

I personally have to admit there is certain beauty to plain C. A lot of headache I have with C++ just goes away, especially when you drop templates. C code can be super elegant, while I have yet to see code in C++ that I wouldn't consider disgusting.

But at the end of the day, I'm more productive using modern C++, STL, templates and all it brings, so there's that.

22

u/ShillingAintEZ Mar 27 '21

If everything you write looks disgusting, then the issue is with you.

-14

u/qoning Mar 27 '21

No, pretty much all C++ code looks disgusting when you look close enough.

7

u/ShillingAintEZ Mar 27 '21

Show me your best C++ that still looks disgusting.

3

u/kuladum Mar 28 '21

I don't understand why you got so many downvotes. The more I look at ancient code, the more I appreciate C style.

-2

u/__shufb Mar 27 '21

I’m with you... I still use templates with the c style c++

0

u/[deleted] Mar 27 '21

[deleted]

-2

u/__shufb Mar 27 '21

There are some links with benchmarks.

0

u/[deleted] Mar 27 '21

[deleted]

3

u/[deleted] Mar 29 '21

The benchmarks are about std::array in debug mode. Which is obviously slower. Nobody is arguing plain arrays are faster at release

-14

u/__shufb Mar 27 '21 edited Mar 27 '21

Stl is still slower in debug than just using raw arrays. It’s insane to use vector to store pixels of image data. These are real things I have seen and optimised.

Even if it was faster or as fast these days I’m not going to go and replace all the calls to malloc and memcpy on buffers in a graphics backend with vectors or std::array... it’s still fine to use c

I even went as far as to say, “I’m not saying don’t use stl, but there are some performance caveats to be aware of”

14

u/serviscope_minor Mar 27 '21

It’s insane to use vector to store pixels of image data.

It's neither insane nor slow. I'd generally reach for an image type, since I like having 2D operations, i.e. 2D indexing and slicing which vector doesn't to. But from a storage point of view, it costs 8 extra bytes on the stack on a 64 bit platform. I think that's a bit of a stretch to call that "insane".

-13

u/__shufb Mar 27 '21

Just don’t see that kind of thing in good engines and you do in naive indie code bases. And I have helped to optimise them and stripping out stl is a good win. And like I say in the post this is about debug performance too

7

u/Crazy_Direction_1084 Mar 28 '21

You can disable STL debug mode within a minute. That really isn’t a good argument to not use STL.

-1

u/__shufb Mar 28 '21

But maybe you want the debug checking of stl in some places, so for processing image data or vertex buffers maybe you can just use something a bit more direct and then still have the stl use in other places in the code base.

I was never saying don’t use stl at all, there are some performance caveats that come with it, and typically a lot of inexperienced coders will go to stl for everything use it badly.

-1

u/__shufb Mar 28 '21 edited Mar 28 '21

The entire article is not about performance at all, I don’t think you read it properly

It covers Pure functions, procedural api’s, hidden implementation and scoped enums, custom code generation (none of which about performance)

Couple of comments about stl performance in debug..

8

u/eliasv Mar 27 '21

Having fast debug builds is nice and all, but who benefits, and at what cost? If you value developer time and happiness then I think the better tradeoff is to use those zero-cost-in-release abstractions and have a more readable codebase with a lower maintenance cost. I know which codebase I'd be more productive in.

2

u/__shufb Mar 27 '21 edited Mar 27 '21

I have nice debug builds and compile times as a result of some of the techniques in the article. This is my coding style that’s all I wanted to share.

We have all this and still have a readable code base... I’m not sure what is not readable about any of the examples I posted. They are just quite simple and very readable.

Some heavily polymorphic and templated c++ code gets a lot more abstract and unreadable.

7

u/t4th Mar 27 '21 edited Mar 27 '21

It depends what you are working on.

For example, event driven programming like GUI software is perfect for OOP. Smart pointers, multi level inheritance and encapsulation are perfect for it.

Games, simulations, etc. that are going over arrays in main loop not so really. Those types of applications are based on performance so branch prediction and cache optimizations are normal things.

I use C++ for embedded programming and i use it as C with cool stuff. I love constexpr, namespaces, simple templates and references. Even having RAII style c-tor and d-tor is usefull sometimes even in inlined code. Just turn off exceptions and I am ready.

The biggest downfalls for me is compilation time, crazy linker errors and variable names for template constructs and sometimes agressive optimization can re-order code is some really unexpected fashion (obviously thats C thing too).

2

u/__shufb Mar 27 '21

Yeah I agree and it’s all about what you are working on. Stuff like ctor dtor and smart pointers were something I used to totally steer clear of and be that performance guy for every bit of code I wrote.

Now in tools I am way more c++ and smart pointers here help a lot with undo/redo systems.

In the post I was just listing the older style patterns I am still using and still like. But I have learned to like c++ more than I used to slowly :)

1

u/t4th Mar 27 '21

But I have learned to like c++ more than I used to slowly :)

Man, I know that story. I was hardcore embedded C guy and it took me years to really appreciate C++.

I understand your findings. It is pretty much what Mike Acton said in his famous CPP con presentation.

7

u/Plazmatic Mar 28 '21

Compilation time wouldn't be nearly as bad if C++ had proper forward declaration on... everything. I have to rely on library writers to either write their code in a way that allows me to forward declare trivially (ie not using typedefs/using wrong), or provide the forward declarations themselves (which they often don't do, GLM gets this right, nlohman json gets this right, VulkanHPP gets this horribly wrong, and there's a whole committee behind that code base). Even when that isn't the problem, the standard library itself gets in the way. I should be able to forward declare every standard library class. Maybe there's some issue with forward declaring causing implementation details to be leaked in undesirable ways that make it harder to make good changes to the language, fine, but they have a solution for that. It's called per include forward companions ie #include<iosfwd>, there should be #include<stringfwd> , #include<algorithmfwd>, #include<tuplefwd> etc. If they instead gave companion forward declaration headers mandated by the standard, It would be even easier because I wouldn't have to do it myself. Instead I'm forced to include <string> every time I want a string, even if it is only for a function, or rely on compiler specific functionality limiting portability massively.

-5

u/dimp_lick_johnson Mar 27 '21

I have a philosophical question to anyone reading. I'm relatively new at C++. I come from a high performance programming in C background but prior to that I wrote backend in Java. I'm working on something that have a very high throughput low latency module and several low performance helper modules. I wrote it all in C a while back, then started rewriting it in C++ for practice. Now the high performance module is too slow compared to C version. Performance loss is beyond acceptable levels. Would it make sense to write the high performance code in a C like manner while keeping the rest in C++. How's the general look on such an approach?

10

u/t4th Mar 27 '21

I wrote it all in C a while back, then started rewriting it in C++

Did you change the structure of the code? I wonder what did you change to lose the performance.

Would it make sense to write the high performance code in a C like manner while keeping the rest in C++

Anything that accomplish your goals is allowed.

When porting C code to C++, i would just firstly throw it in C++ compiler, then change C arrays to std::array to look for out of bound hidden errors. Then removing memory allocations. Changing pointer passing argments to references and so on.

If you blindly follow OOP to rewrite more sequential/structural approach then losing performance is easy to fall into.

-3

u/dimp_lick_johnson Mar 27 '21

I wrote from scratch and strictly followed OOP as if I was writing Java, which was second nature thanks to my Java background. I did it to practice OOP C++, it wasn't a serious attempt at first but the rewrite turned out more maintainable and easier to digest so I decided to make it the main project if I can make the main module faster.

Anything that accomplish your goals is allowed.

I can't agree with that. To me, things that make the code base unmaintainable are not ok. I've seen enough gag inducing code to be strict about this. I'm just not sure if pairing structural C++ and OOP C++ is gag inducing to experienced C++ developers.

9

u/Wouter-van-Ooijen Mar 28 '21

strictly followed OOP as if I was writing Java

So what you wrote was a nice excercise, but it should be clear from the start that this was something you would throw away when the excercise was done.

C++ might allow an everything is a (heap allocated!) object Java style, but that doesn't mean you should use that style if your goal is anything but writing Java in C++.

12

u/ShillingAintEZ Mar 27 '21

Java style 'OOP' is terrible in any language. It is likely that you would see massive speedups from just using arrays of structs.

2

u/dimp_lick_johnson Mar 27 '21

What do you mean by array of structs? What would I use it in place of?

2

u/ShillingAintEZ Mar 27 '21

You would use it in place of everything that you can. Anywhere you just need to loop through a sequence.

Allocating each instance with new is a performance killer and accessing them through a pointer is a performance killer.

2

u/Wouter-van-Ooijen Mar 28 '21

To me, things that make the code base unmaintainable are not ok.

Then obviously maintainble code is one of your goals! Include it the goals you want to accomplish.

1

u/__shufb Mar 27 '21

If you are forcing OOP and trying for performance it might not be the right tool for the job. I would write data oriented code for performance and not worry too much about OO myself, data oriented and object oriented code can still co-exist

-1

u/dimp_lick_johnson Mar 27 '21

I forced OOP to learn OOP C++. Then it turned out better that C version in some ways. I'm cautious about how to structure OOP and non-OOP code and how to have them interact each other. I'm worried about lifetimes.

4

u/[deleted] Mar 27 '21

Stop reading on

In order to get this to compile we need to include massive_header_file.h

After that i expect to see strcpy(0, 0) (you can shoot in the knee), so when you wrote bad design you cannot expect magical better code. In the real world you can use modules.

3

u/__shufb Mar 27 '21

But a lot of real world code bases I have worked on have done stuff like that and before modules this shows how you can use hidden implementations.

1

u/[deleted] Mar 28 '21

It's easy to do, modules just ensures you do it right https://en.cppreference.com/w/cpp/language/pimpl

1

u/__shufb Mar 28 '21

In the post I only showed pure virtual interface with inheritance and procedural c-style api, but yes pimpl had been useful to me in the past as well

8

u/ShillingAintEZ Mar 27 '21 edited Mar 28 '21

Then to be clear, when you said 'you need to include' you actually meant 'I saw this done'.

14

u/Dean_Roddey Mar 28 '21

Some of us take the middle road, taking advantage of modern C++ keywords that help express intent or let the compiler watch our backs more, very much using OOP features but not in the over the top Java way, very much using inheritance but no deep hierarchies, using templates where they really count but very much avoiding the modern "everything is a template" syndrome, not hyper optimizing from the word go and introducing massive complexity that isn't provably required.

5

u/TheSuperWig Mar 27 '21

Could do with some proofreading.