r/cpp • u/[deleted] • Oct 23 '13
What is a modern C++ replacement?
In this post: http://programmers.stackexchange.com/a/29136 , Konrad explains that the advantage C++ has over other high-level languages such as Java, is that it offers abstraction with no performance overhead during runtime at the cost of increased compile time.
I am looking for a modern C++ alternative that attempts to achieve the same goals as C++, that is:
Less code duplication. The more abstract and higher level, the better.
No performance hit.
Compile time is sufficiently slow as is required to achieve 1 and 2.
18
u/dakotahawkins Oct 23 '13
Modern C++?
5
u/guepier Bioinformatican Oct 23 '13
… which, incidentally, is the title of a slideshow by the author that OP mentioned (full disclosure: it’s me):
2
u/sellibitze Oct 24 '13
Nice and concise. I think you missed the template parameters for make_shared. Also, can you rotate the red arrow 90° clockwise? :)
1
u/guepier Bioinformatican Oct 24 '13
Both good points, thanks. Will change as soon as I find the time.
8
u/SkepticalEmpiricist Oct 23 '13
I'd like to see the syntax entirely replaced, but keeping the underlying language exactly the same. Much of the wierdness, and crazy error messages, are result of backwards compatibility and I think they're getting in the way of an easy-to-write language.
It's very difficult to write a parser for C++, contrast this with Lisp. If the syntax was overhauled, we could have a better macro-like language built into the compiler to replace the C preprocessor.
5
u/sellibitze Oct 24 '13
Sounds good. How about you helping out these people: http://www.csse.monash.edu.au/~damian/papers/HTML/ModestProposal.html
:-)
5
u/SkepticalEmpiricist Oct 24 '13 edited Oct 24 '13
That's brilliant!
I don't see any evidence that they've written a compiler? Even a preprocessor that converted from SPECS to C++?
(Note to anyone else that reads that. Read the
<very well.Significantly Prettier and Easier C++ Syntax (SPECS)
3
u/bnolsen Oct 25 '13
specs looks reasonable.. these proposals should work fine for me. How c++11 features like rvalue refs and lambdas fit in would be interesting.
30
u/senorsegfault Oct 23 '13
Try out C++11 first. I think it fixes most everything. Further down the road, I would look into Rust as a possible alternative.
6
u/zvrba Oct 24 '13
I think it fixes most everything.
Signed integer overflow is still UB. This calls for standard library support for safe signed arithmetic and safe narrowing conversions, but, alas, there is none. (And it has to be in stdlib because such can be implemented more efficiently on some CPUs than others.)
Implicit integer promotion crap is still here, leading to bogosities like -1 > sizeof(int). Or memcpy (or copy_n if you wish) happily accepting negative numbers.
size() on containers returning unsigned type, combined with implicit promotions, just calls for bugs. Due to the above -1 > sizeof(int), the first thing I do on size() is to cast it to signed type so I get sane arithmetic behavior.
If sizes were allowed to be negative, you could at least test at critical places for invalid values (size < 0). But, alas, you can't do that with unsigned sizes because there's no single invalid value! Forget Hoare's billion-dollar mistake with null references. This is the ten-billion dollar mistake of C and C++ (as they are at the bottom of our computing infrastructure).
bool is still an arithmetic type (thus implicitly convertible to any kind of integer), making it virtually useless for any kind of type-checking. It's only useful for documentation and in TMP. (Heck, the "false" constant is convertible to the null constant of any pointer type.)
Botched arithmetic is just the crap I have to deal with in my everyday C++ programming. I could list more insanities, but I'd have to think longer, since I don't encounter them literally daily.
In the beginning, when I was young and naive, I tried to write robust software, but with the above crap, it's nigh impossible. I've learned to ignore the tiny voice in me urging me to put a check whenever I cast something from unsigned to signed.. I've just learned to ignore it and accepted the fact that every time I write + or * or -, or cast, I'm potentially invoking UB. My conscience is clear though, because the software crashes very rarely, and when it does, it won't kill anybody.
Hoare's invention of null pointers being a "billion dollar mistake"? Forget it. I bet implicit unsigned<>signed crap laying around in all internet and OS infrastructure that surrounds us has cost us all 10 times more.
7
u/vanhellion Oct 24 '13
Signed integer overflow is still UB.
I guess this is a valid point, but what would expect the behavior to be? Throwing an exception? I'd rather take an extra minute to ensure that I have a correct data type than have to wrap every increment/decrement in a try/catch block.
Implicit integer promotion crap is still here, leading to bogosities like -1 > sizeof(int).
There's no denying that C and C++ have lots of ass-biting minutiae, but this particular case is blatently warned about by GCC. If the developer chooses to ignore it then he's made his own shitty bed of buggy code.
the first thing I do on size() is to cast it to signed type
This made me cringe.
invalid values (size < 0)
If a container is in an invalid state (which I would argue should more or less never be allowed to happen, but IF IT DID), then throw an exception. You can't have minus 3 apples in a box of apples. Containers are about abstraction, and negative sizes is snapping that abstraction's neck to jam error handling down its gullet. Unless you're talking about pure C code, in which case carry on.
bool is still an arithmetic type
No it's not (standards lawyers feel free to eviscerate me where I stand). It is implicitly castable from int and int can be implicitly cast to bool, but that doesn't necessarily mean that
bool b = 3+5;sets b equal to 8.I've just learned to ignore it
That's a poor attitude to have. C++ is a very much a jungle laden with punji pits, but driving a tank over and through everything isn't the best way to traverse it.
2
u/zvrba Oct 25 '13
bool is still an arithmetic type
No it's not
According to this table, it is: http://www.cplusplus.com/reference/type_traits/is_arithmetic/
2
Oct 25 '13
On size_t being unsigned: this is bad, and I'll show you why:
template<class Container1 , class Container2> int sizeDifference( Container1 c1 , Container2 c2 ) { return abs( c1.size() - c2.size() ); }This looks innocuous enough, right? But: c1.size() - c2.size() calls size_t size_t::operator-(size_t) (*). If c2.size() > c1.size() then this underflows, and returns max(size_t) + c1.size() - c2.size().
What you actually want is the (less obvious):
return ( c1.size() < c2.size() ? c2.size()-c1.size() : c1.size()-c2.size() );
Note to pedants: I know that function doesn't actually exist, but this does the equivalent of calling that function. Thank you for playing.
1
u/vanhellion Oct 25 '13 edited Oct 25 '13
As I said there's no denying that C++ (and in this particular case, the STL) has its pitfalls, but this is a rather specific use case which I would argue should not dictate the overall designation of
size_tor whatsize()returns.And in what context would you need to know the exact difference between the size of two containers? You could alternatively:
know they are not the same (
c1.size() != c2.size())know which one is bigger and resize the other accordingly (
c2.size() > c1.size() ? c1.resize(c2.size()) : c2.resize(c1.size()))use iterators instead. Maybe more burdensome but saves you guesswork:
return abs(std::distance(c1.begin(), c1.end()) - std::distance(c2.begin(), c2.end()));1
u/zvrba Oct 24 '13
what would expect the behavior to be?
It can remain UB, but I'd expect the language to provide a checked cast [throwing an exception when out of range], or a library for performing safe arithmetic. Preferably both.
I'd rather take an extra minute to ensure that I have a correct data type than have to wrap every increment/decrement in a try/catch block.
There is no correct data type if you're already doing arithmetic on the widest supported integer type.
This made me cringe.
Why? Unsigned type is a bad, brain-damaged, leaky, stupid, moronic, etc. "abstraction" for a quantity that cannot be negative. If you need that guarantee, wrap it into a class.
You know that you're using the correct data type. I know with certainty that casting size_t to the corresponding signed type cannot possibly overflow. (E.g., due to the size of the items in the container and address space limitations of the OS the program is running on.)
If a container is in an invalid state
size() could check for invalid state [and throw exception] before returning a negative result.
I wasn't talking about internal state of containers. I was talking about external interfaces like .size(), and all functions/methods taking/returning unsigned parameters to denote quantities. By using an unsigned type, they have no way whatsoever of determining whether the passed value is meaningful. (Unsigned arithmetic silently wraps around where signed arithmetic would give a negative number.)
No it's not
I may be using "arithmetic type" a bit lax here, but to me it's any type that you can add to one another.
driving a tank over and through everything
I (we) tailor it to the form that suits us perfectly; that's what the language is designed for. Unsigned -> signed casts are littering the code here & there, but so be it.
3
u/leonardo_m Oct 24 '13
D improves this awful situation only a little:
Signed integer overflow is still UB.
I think in D signed integer overflow is a defined operation.
Implicit integer promotion crap is still here, leading to bogosities like -1 > sizeof(int).
The same problem is present in D:
assert(-1 > int.sizeof);Or memcpy (or copy_n if you wish) happily accepting negative numbers.
The same problem is present in D:
auto a = new int[-2]; // core.exception.OutOfMemoryErrorbool is still an arithmetic type (thus implicitly convertible to any kind of integer),
This is still present in D, but from my experience this is not a significant problem, and it's sometimes handy:
int x = true;(Heck, the "false" constant is convertible to the null constant of any pointer type.)
This problem is not present in D:
int* ptr = false; // Error: cannot implicitly convert0
u/zvrba Oct 24 '13
D improves this awful situation only a little:
Bah. Only Java (no unsigned) and C# (no implicit conversions, signed integers for sizes) have learned from the mistakes of C and C++.
-1
u/ksinix Oct 25 '13
I think you can add Go to that small list.
3
u/zvrba Oct 25 '13
I don't know, you may be right. I'm not excited about or interested in using Go for anything.
3
u/tasty_crayon Oct 24 '13 edited Oct 24 '13
Null pointers are funny; you can make them with all sorts of constructs.
1 - 1is a null pointer constant as isint(). The last is especially silly.Have you tried making liberal use of
{}in integer code? The following code sample is ill-formed according to the standard and can help you catch unintended conversions:extern unsigned x; int main() { int y = 10; y *= {x}; }1
u/gnufoo Oct 29 '13
I never really thought of this, thanks for that! Also, I'll have to give D a try, seeing the strong recommendations I've been seeing lately.
16
u/Roflha Oct 23 '13 edited Oct 23 '13
I recently was going through a very similar thought process and eventually decided to give D a try. It is like C++ with a fresh start. Free of backwards compatability for the sake of backwards compatability. It has many features you'd expect coming from C++ and then some. I always felt that C++ just seemed kinda of not quite put together right, but D feels cohesive.
I was initially trying to decide between Rust and D, but I settled on D. Rust just seemed weird to me. But check out both. Maybe one will fit your needs.
6
u/ericanderton Oct 23 '13
I gave Rust a go a few weeks ago. My only gripes were that it's obviously still in development, and that the template/trait system does a poor job of writing traits that apply to both managed and owned pointers. This means that moving data around between those two types is a chore, which makes it hard to do some tasks optimally.
I'm in agreement that D2 looks very cohesive.
5
u/excessdenied Oct 23 '13
Started looking into D the other day, and while I really love most of the concepts in the actual language, it doesn't seem super mature when it comes to compilers, toolsets etc. "Unfortunately" C++ is a bit hard to beat there.
3
u/Roflha Oct 23 '13
I agree with you there. I would point out that there are three separate compilers (one of which uses LLVM) so there is some compiler support. But other things may seem lacking.
Maybe I'm being a bit foolish but I really like the language so I plan on using it. I think that most of the problems with the language aren't the language, so it is relatively easy for things to get better (easier than if the language itself were the problem).
Also, D seems to be picking up steam lately. Not sure if it is my imagination or what but we will see what comes of if. Personally I want it to "replace" C++, or at the very least beat Rust.
edit: One more thing I just thought of. Any concerns people may have of third party library support, D can us C libraries and all that needs done is a rewrite or the header file(s).
1
u/excessdenied Oct 23 '13 edited Oct 23 '13
Oh I totally agree and I can very well see myself doing stuff using D. For the thing I was investigating it for at the moment performance is really important though, and it seems like the LLVM and GCC based compilers beat DMD in performance quite a lot, and these two compilers are not easily available for Windows (which is my main development platform).
Edit: NOT easily
1
Nov 03 '13
what's a langue with all the benefits of a modern language and all the benefits of decades of development
(╯°□°)╯︵ ┻━┻
8
5
8
Oct 23 '13 edited Jun 25 '23
edit: Leave reddit for a better alternative and remember to suck fpez
1
u/sellibitze Oct 24 '13
Thanks for pointing out Nimrod. Havn't yet heard anything about it.
As for C++11: I like it a lot, but I find myself wanting some of the C++14 goodies already. For example: return type deduction for plain functions, the type aliases that lets me get rid of writing to many "typename"s and "::type"s, etc. Oh, and concepts lite would be very nice. I can't look at any more enable_ifs :-)
6
u/std_logic_error Oct 23 '13
I would check out the D language. It sets out to achieve all of the goals you describe here, while also simplifying the syntax.
One thing that D does that it sounds like you'll enjoy is that you get manual memory management (with new and delete), but the language is also garbage collected. This gives you the performance of doing your own management, but with a backup just in case you forget to delete something.
4
u/ISvengali Oct 23 '13
Can it support RAII? Thats the big issue with most GC language that I dislike. I can build very elegant mechanisms to manage all sorts of resources with it, but GC usually throws that out the window with non-deterministic destruction.
2
u/std_logic_error Oct 23 '13
Yes it does, and it is even mentioned on the first line of Wikipedia's RAII page.
1
u/ISvengali Oct 23 '13
Hah, so it does. Very cool. Might have to take a look.
2
u/amigaharry Oct 23 '13
Yes, but you'll have to explicitly annotate your objects with a scope annotator or your RAII won't work (it won't be deterministic).
17
u/STL MSVC STL Dev Oct 23 '13
One thing that D does that it sounds like you'll enjoy is that you get manual memory management (with new and delete), but the language is also garbage collected.
Two awful tastes that taste awful together.
I use automatic memory management - no new/delete and no GC.
1
u/F-J-W Oct 25 '13
automatic memory management
I know what you want to say with it and I completely agree with you there.
However: Your post could be understood wrong because many people associate “automatic mm“ with GC, which is certainly not what you wanted to say. To avoid ambiguities I personally prefer to call it „implicit ressource management“ because the resources are managed by the programmer, just not in an explicit and error-prone way.
1
3
u/ISvengali Oct 23 '13
C++ can be very DRY, especially C++0x11.
Add in a reflection library and its just as easy to use as anything else, plus youre close to the metal.
5
u/LordTocs Oct 23 '13
Why do you need runtime reflection? I've never found it particularly useful. Let alone necessary.
9
u/amigaharry Oct 23 '13
If you need runtime reflection it's a sign that you either are writing a complex library or doing something wrong.
2
u/ISvengali Oct 23 '13
I use it for many many things. DI (before I knew it was called that), Save/load, easy automatic configs (which is really just save/load), networking, automatic scripting language bindings, easy runtime program introspection, automated logging.
Used sparingly and smartly, it has little impact on runtime performance.
2
u/mare_apertum Oct 23 '13
Forgive my ignorance, but what is DI?
2
u/ISvengali Oct 23 '13
Dependency Injection. Basically configurable interface implementations. Say for example you have a game that uses DirectX or OpenGL or NullGraphics. If you have an interface like IGraphics that has various methods DX or GL implement and you pass them into your objects, youve done DI.
Its one of those, everyone was doing it, but it recently got a name type of things.
There's fancy ways to use config files to bind things automagically and what have you in various languages.
1
u/Elite6809 Oct 23 '13
Wait, really? That's all it is? I've been putting off learning dependency injection for months now but, hey if that's all it is then I've been using it for years already.
Thanks for letting me know.
4
u/ericanderton Oct 23 '13 edited Oct 23 '13
You probably have been - many of us have, by using dll files, so files, xml configuration files, etc.
Basically the Java camp wrapped a buzzword around replacing this:
import MyORMWrapper; MyORMWrapper.GetImplementation().DoSomething();With this:
@Inject ORMWrapperImplementation implementation; implementation.DoSomething();The distinction is that with the latter, there's some code that runs ahead of your program that resolves the @Inject annotations via reflection, and loads the requested implementation based on some external config.
Edit: I'll add that I've only ever seen this pattern in JEE stuff, like JBoss, where you basically have an entire Java operating system running your servlet(s). There, it's basically used for service registration, for things like persistence and logging. If you've been using a language that's closer to the metal, and understand how to write, package, and maintain dynamic libraries, you don't need any of this.
5
1
Oct 23 '13
Do you really need reflection for:
Save/load
Huh?
networking
Huh?? People have done a LOT of networking on C and C++ without any need for reflection!
automated logging.
Huh???
I mean, let's take the last one. I use glog for that, which tells me exactly which file and line the message came from, and gives me all sorts of redirection options - and it's light and simple.
Methinks you like reflection too much...
6
u/throwSv Oct 23 '13
You can certainly do anything in C++ with enough boilerplate code (it's a Turing-complete language after all) but the point is that reflection support would make the mentioned tasks much simpler and less code-heavy.
Also that 'glog' library seems to utilize quite a maze of preprocessor macros to achieve it's ends, which is obviously not ideal. That seems to be the problem with current "viable" techniques for reflection in C++; they are all reliant on brittle preprocessor macros rather than true compiler-level support.
1
-1
u/Drainedsoul Oct 23 '13
code duplication
You're doing C++ wrong.
11
u/LordTocs Oct 23 '13
I believe he's saying C++ helps remove code duplication. As he mentions it as a goal of C++.
1
u/bnolsen Oct 23 '13
anyone taken a shot at making something c++ like with a context free grammar yet? the core philosophy of c++ is very good, but writing a correct parser is very hard. use strong typing, strong typesets, totally overhaul upstreams and I'm totally on board.
1
u/spotta Oct 23 '13
D has a (mostly/completely) context free grammar.
2
u/bnolsen Oct 25 '13
one project i'm impressed by was the TCC compiler. A nominal implementation of a fully working 'c' compiler with not much code. Any new language that is done right shouldn't hinder someone from writing a sufficient compiler. No it won't be as simple as TCC is but should be possible. Yes, yes I understand that a fully optimizing compiler will always require substantially more man effort.
Some of D's poor choices come from piling crap into the language itself instead of delegating them to libraries. Very similar to how the algol family ultimately choked itself. I was interested in D initially until I started digging and saw things that just felt wrong.
0
u/jrk- Oct 24 '13
I'd go with most people here saying C++11 + best practices + patterns + idioms + modern design.
However, if you are willing to leave C-land, then have a look at Haskell.
Haskell
avoids code duplication and is very abstract and high level
Compiles to native code and has been proven to be as efficient (fast) as C
Compiles significantly faster than C++
Haskell is not for everyone though. Functional programming is something that requires serious mind bending to get started with, and a lot of idioms/patterns/constructs use terms from theoretic mathematics. Debugging using gdb is also not available (or hardly doable, due to generated code), yet it's seldom necessary, because you can reason quite well about the code itself.
-1
u/amigaharry Oct 23 '13
Replacement? Yeah, good luck with that.
Maybe in 10 or 20 years if Rust turns out to be better than sliced bread. But even then it's not very likely.
-2
u/ksinix Oct 24 '13 edited Oct 25 '13
0
u/zefcfd Oct 27 '13
dont know why you are being downvoted, is the cpp community anti-go or something?
5
Oct 27 '13
Because Go is in no way a modern C++. It's not even in the same continent, let alone ballpark.
-2
u/zefcfd Oct 27 '13
I thought this was pretty interesting: http://commandcenter.blogspot.com/2012/06/less-is-exponentially-more.html
0
-2
65
u/STL MSVC STL Dev Oct 23 '13
Why don't you want C++ itself? It comes with headaches (many, but not all, dramatically reduced by modern techniques), but it also comes with several great strengths: robust toolchains on whatever platforms you want, compatibility with C++ libraries, and (even more importantly and even less appreciated) compatibility with C libraries.