196 points · by eklitzke · 9y ago · 331 comments
The thing is, of all the languages I code in C++ is my favorite. It is the most performant (using C where necessary), and is as easy to code in as JavaScript IMO. C++14 (and higher) feels like coding in Go or Python.
I feel most people don't actually have experience enough with modern C++ and are trying to use the 90's version of C++. The 90's version is awful, and even the modern has a few quirks. However, when you need performance and something less than C it's amazing.
There are no channels, there are no lightweight/green threads, there's no standard HTTP library, no standard crypto libraries, no standard test framework. For certain classes of applications this makes Go significantly more productive and significantly less bug/error prone. Not to mention compile times.
Even the nicest things in C++14 suffer from backwards-compatility-ism i.e. awkward syntax, and endless incomprehensible garbage output from the compiler when you make an error e.g. inside some complex templated code. As C++ devs we manage to live with that stuff but it still sucks.
Even if your code uses some nicer subset with standard libraries you typically need to interface to a whole range of things that do not comply with that subset. Be that something like a Cassandra driver that uses libuv or OpenSSL with its native C interface. Any C++14 beauty that may have existed is gone and your code is now subject to all those subtle memory management, buffer overflow, and concurrency issues.
I used to think garbage collection was garbage but I've start to appreciate how much simpler it makes my life (Even over RAII smart pointers) for very little cost in Go.
Python, Ruby and Javascript are a completely different kind of language so I'm not sure it's worthwhile comparing those to C++. There are many things you can do in Python that you can't do in C++ and that's mostly a good thing ;)
That said there are certainly some classes of applications where there's no substitute to C++. It's also much nicer than it used to be. But it shows its age.
I usually build embedded systems, desktop apps, and even some higher end computing applications. I use QT in conjunction when I need most of that stuff you mentioned, as that framework makes it easy. Also,
> there's no standard HTTP library
I mean, there isn't a standard library, but cURL is easy to use.
I've used C++ with Qt in building embedded applications and my experience was mostly good. Then again Qt had its own types which were incompatible with C++ and a fair bit of work was getting more or less standard C++ mated with Qt. I remember writing a lot of glue code that used Boost.Signals2 ...
On one hand it's true that people who still see C++ as C with classes and don't use things like lambdas, algorithms, smart pointers, STL data structures, are contributing to some hate/misunderstanding of C++. On the other hand, C++ developers who do use the modern features get used to all the quirks and don't understand why others don't see what we see ;) So we just maybe std::move, or inherit from enabled_share_from_this without thinking twice and know the difference between && and & and the new lambda syntax but really, as a developer, most of the time, why should I care? To some extent a camel can't see its own hump.
What you're saying is basically exactly what I would have said 2 years ago before I started using Go more heavily. Now it's mostly C++ because I have to and Go because I want to... Not that Go is perfect but the stuff that it does well it also does easy.
Unless you want windows compatibility. GP isn't necessarily doing web development from the description though, just something that uses a network.
The fact that there is a nice subset of C++ which works well is not a valid argument, in practice. As you say, you are forced to include in your projects a lot of libraries, each assuming its own definition of what this subset is, and the union of those subsets can be a monster.
So for some sanity, I always spent some days writing sane, type safe, C++ wrappers.
But this always fails flat when working in teams that don't share the same quality goals, without directives from above.
Thought-trough, modern C++ code is IMHO quite often more readable, elegant and generally more pleasant than anything I've seen in C# or Java so far. But it's all hampered by the poor code some people ham-fisted in before or afterwards...
So, at least for me, C++'s biggest drawbacks are many of its users, not the language itself. Interestingly, that's something thad e.g. the Python community seems to have way more success managing, although Python as a language checks almost all boxes that should - in theory - foster quick hacks...
There are a few things that I'm still not quite happy with.
* It's still incredibly cumbersome to set up a project
* Setting up a proper build system is tedious, especially if you're targeting multiple platforms.
* I'm missing some "functional" methods attached to the collections, e.g. find, filter, map, some, each, ... Afaik some of them exist as functions that take 2 iterators and a lambda but that's just plain ugly and unreadable. Instead of
std::find_if(list.begin(), list.end(), condition});
I'd like something like list.find(condition);If you already have a compiler installed, you can go from nothing to knowing how to build a library, executable and an installer for multiple platforms in just a couple of hours with the CMake tutorial: https://cmake.org/cmake-tutorial/
If I want to use an external library in a C++ project, I need to:
* download it from the website / GitHub
* build it from source
* add the library into my CMake file.
Whereas in Gradle, I add a single line to one file and the library is installed on my next build attempt. Full stop. There are no more steps.
C++ makes it searingly painful to get a project going. I'm honestly afraid to add any new libraries to my projects because I know that (at minimum) that means I'm sacrificing an afternoon to resolving new errors.
- automatically collects executables to build from the .cpp files in two distinct directories
- uses the CPP preprocessor to only link in the object files in the rest of the project associated to headers used directly or indirectly by the executable .cpp files
- allows me to select the compiler using an environment variable
- allows me to pre-define some common options for the three supported compilers (e.g. to disable specific warnings with ICPC and increase the template instantiation depth for Clang)
- allows me to specify whether I want to rebuild everything or just a single executable and whether this should be copied into the external directory contained in my $PATH
Yes, putting this together was a bit of work (208 lines for the Makefile, 34 for the dependency generator and 15 for the script which puts the current output of `git diff` into a CPP #define), but now it only rebuilds the things needed, only links in the object files needed and allows me to quickly test multiple compilers. Getting all this with CMake seemed extremely difficult when I last looked at it.
Addendum: I should add that my only external dependency is Boost and LAPACK and I essentially ask the user to point me at their Boost base directory and plug in their LAPACK link line -- this works well for the target audience (fellow physicists who are used to all sorts of horrible toolkit installation processes), but I understand it may be annoying to the more general public (or if you have more external dependencies).
Also, you can do stuff like auto blah = with( list ) << sort( ) << filter( predicate ); now. It's not in the std lib but it is doable
First, there are containers that do have a find() method, std::map, for example (although not on a condition). It could be a wrong impression, but to me this tells something. Perhaps, if I intend to do a search, I might be better off using a different structure (rather than a list) that is more suitable for searching, or maybe a different - more efficient - algorithm (such as binary_search(), if applicable).
Second, if you use a container as a part of your own class, defining a find() method is trivial.
I have no doubt that there are other, more technical reasons for the standard library being the way it is, for example, the idea of separation of algorithms from containers by means of iterators.
And functions like map (apply function to each element of a collection), filter (return new collection with all elements that match a condition) and possibly some others have to be applied to all elements in a collection anyway.
> Second, if you use a container as a part of your own class, defining a find() method is trivial.
It is, but I'd rather not have to define 20 trivial things when I start a new project.
There is a tool called waf (https://github.com/waf-project/waf) which is getting way too little love, but is really the perfect build system for C and C++ projects:
from glob import glob
def options(ctx):
ctx.load('compiler_cxx')
def configure(ctx):
ctx.load('compiler_cxx')
def build(ctx):
ctx.program(source = glob('src/*.cpp'), target = 'your-program')
That build script will work with all major compilers (Visual Studio, gcc, clang, mingw) out of the box. random_device rd; // non-deterministic generator
mt19937 gen(rd());
uniform_int_distribution<> dist(4, 18);
// for testing purposes, produce byte stream that from lines of text
auto bytes = range(0, 10) |
flat_map([&](int i){
auto body = from((uint8_t)('A' + i)) |
repeat(dist(gen)) |
as_dynamic();
auto delim = from((uint8_t)'\r');
return from(body, delim) | concat();
}) |
window(17) |
flat_map([](observable<uint8_t> w){
return w |
reduce(
vector<uint8_t>(),
[](vector<uint8_t> v, uint8_t b){
v.push_back(b);
return v;
}) |
as_dynamic();
}) |
tap([](vector<uint8_t>& v){
// print input packet of bytes
copy(v.begin(), v.end(), ostream_iterator<long>(cout, " "));
cout << endl;
});
//
// recover lines of text from byte stream
//
auto removespaces = [](string s){
s.erase(remove_if(s.begin(), s.end(), ::isspace), s.end());
return s;
};
// create strings split on \r
auto strings = bytes |
concat_map([](vector<uint8_t> v){
string s(v.begin(), v.end());
regex delim(R"/(\r)/");
cregex_token_iterator cursor(&s[0], &s[0] + s.size(), delim, {-1, 0});
cregex_token_iterator end;
vector<string> splits(cursor, end);
return iterate(move(splits));
}) |
filter([](const string& s){
return !s.empty();
}) |
publish() |
ref_count();
// filter to last string in each line
auto closes = strings |
filter(
[](const string& s){
return s.back() == '\r';
}) |
Rx::map([](const string&){return 0;});
// group strings by line
auto linewindows = strings |
window_toggle(closes | start_with(0), [=](int){return closes;});
// reduce the strings for a line into one string
auto lines = linewindows |
flat_map([&](observable<string> w) {
return w | start_with<string>("") | sum() | Rx::map(removespaces);
});
// print result
lines |
subscribe<string>(println(cout));
[1] https://github.com/Reactive-Extensions/RxCppC++ 11 and 14 don't do anything in terms of build times AFAIK -- they probably make them worse. I'm hopeful that modules will make a difference, but at first glance they seem awfully complex.
And also metaprogramming. In Python, I use Python for metaprogramming. In C++ I have to switch to this weird template language. I'm a template user, and they are mostly great to use, except for build times. Template authors are a completely different kind of C++ programmer.
This was added in C++11.
In the header you state something like:
template <typename _Tp>
class Example {
};
extern template class Example<int>;
In some CPP file you write: template class Example<int>;
At that point any calls to Example<int> will not be resolved by callers. They will simply expect the template to be available at link-time. Theoretically this could be slightly slower (I think), since method calls will cross translation units rather than being inlined. But it does cut down on compile times.https://msdn.microsoft.com/en-us/library/by56e477.aspx
> Note: The extern keyword in the specialization only applies to member functions defined outside of the body of the class. Functions defined inside the class declaration are considered inline functions and are always instantiated.
I understand what you are saying but for a newcomer it's hard to discern the differences as in "oh thats a very 90s way or thats a very C++ revision xx way of doing things." I think this is part of what makes it so overwhelming to learn. The scope of the language is already quite large and then when you pile the different versions on top of that.
I am curious if you could share any advice on that for a newcomer to C++?
Is it practical to only learn the most recent revision/standard? I would thing its good to know the good and bad if only to understand what rev or style you are looking at without being confused. But maybe that's not necessary or practical?
These were already possible even before C++98 got released.
- Code new work or updates in as little time as possible
- Let a large group of devs of varying skills produce a high quality code base with the least amount of overhead/rules/babysitting
- Achieve the the best defect rate/quality given finite time
- Require the lowest cognitive load to reason about things
- Performance is high enough to meet a point of diminishing returns given the problem at hand
In my opinion, no existing language satisfies these two simultaneously:
> - Let a large group of devs of varying skills produce a high quality code base with the least amount of overhead/rules/babysitting
> - Performance is high enough to meet a point of diminishing returns given the problem at hand
Do people "enjoy" C++ because they weighed the important concerns and thought it was the best objective choice for their work overall? If so I understand it, otherwise we're talking about a hobby language.
What do you mean by "most performant"? Is there some meaningful difference between that phrase vs. "fastest"?
C++17 is so full of good stuff I'm considering beta compilers just to get it. Soon Python and Ruby won't have any advantages left in writing beautiful, clear, correct, bug-free, and easy to read code and C++ will still run 200x faster.
Structured bindings are going to be amazing! Yea we didn't get modules, but I for one am psyched about this feature alone.
If only they were faster to upgrade compilers at work...
Come on, it's not like they've added garbage collection.
The clever combination of declarative management for common cases and reference counting for complicated cases looks like the winner in the long run.
I mean we have destructors which handle so much more than garbage memory.
Close files, release mutexes, close sockets, cleanup thread pools, manage the lifetime of anything. One time I opened a web browser in the constructor and closed it in the destructor, and I had full confidence that no matter what crap happened in the middle my app never leaked whole browsers.
So it's totally doable in library without cost to those that do not need it.
Does that mean C++17 will finally get support for the generator pattern?
But there will be books, and good ones. Next year probably. The compilers aren't even ready yet.
IMO, C++ has both a lot of necessary complexity (due to its lofty goals) and a lot of unnecessary complexity (mostly due to the C back-compat). I think this is the root of a lot of the "C++ sucks!"/"C++ is great!" arguments; when people only see one half or the other.
My bottom line with C++ is that it tries and mostly succeeds to do a lot of hard things, but has questionable design decisions that make these things even harder than they need to be. For a while we just had to live with that because if you wanted a language that was both fast and high-level, C++ was the only game in town. I think that's no longer true, which is why I'm such a cheerleader for Rust: I see it as trying to have all the good things (necessary complexity) of C++ without the baggage.
C++ is more like an ecosystem of about a dozen languages. You can divide it into 4 languages chronologically. You can add a lot more by categorizing by use. If you pick and choose properly, you can set up a subset of C++ that makes it a great language. Half the computer programming managers out there have below average taste, however.
This is one reason why I doubt adding more features to C++ (making it 5) is going to make the language any more pleasant to use (outside toy, one person programs).
Which describes my current work situation. However, this would seem to imply that a startup or a small project would be able to set up a C++ project with a beautiful, cohesive subset of C++. Your point is something that people who are serious about language design for programming "in the large" should definitely pay attention to.
This is one reason why I doubt adding more features to C++ (making it 5) is going to make the language any more pleasant to use (outside toy, one person programs).
How do you distinguish between one, two, three, or four person projects? Can you really make such a blanket statement about all the different possible codebases that exist? Methinks you exaggerate.
(And I say this as a former dyed-in-the-wool minimalist Smalltalker!)
It's dealing with an existing code-base or team that doesn't agree on what "awesome" is or supporting old compiler/platforms or 3rd-party dependencies that turns C++ into a nightmare.
Basically, C++14/17 is an awesome language when working on your own thing, in a vacuum, without any dependencies.
Rust and Haskell are complex languages (as compared to say C). And it's not clear for a lot of people that their complexity is any better than C++. But by trying to garanty an ever increasing level of correctness and safety, they booth creating a large set of computation that are conceptually easy but very hard to express in a way that is correct to the type system/borrow checker.
I actually like modern C++ well enough for the niche described here; lambdas (and the control they offer over captured variables), type deduction, ranged fors and the like make it pleasant enough to write for being as performant as it can be. I've written many more lines of C++ than Rust. But it's still apparent that language-enforced invariants are quite a different species from conventions that will enable safe programs if everyone uses them correctly at all times. You can maybe guarantee that for a team, but can you guarantee it for several teams? Can you guarantee it for every external dependency?
I can imagine plenty of pragmatic analyses today ending up with C++ as the ideal choice of language, but the monomaniacal focus on Performance ignores ecological concerns like these and also mostly doesn't grapple with the fact that there's plenty of low-hanging fruit to get to performance-wise in any project before something like a fundamental 1.2x performance penalty on Rust's part really matters, especially considering how domain-dependent that number is likely to be. Pure speed is a pretty poisonous obsession in our field, IMO, and I think we've reaped the whirlwind for it already. It's time for a more holistic outlook.
Meanwhile, there is also this tendency of software getting slower, and this other tendency of code getting trashed because it was written as a short term solution.
C++ is designed for high quality, meaning taking more time to write a better solution. It's more thought towards industrial long term quality than market quality. I guess a bad analogy would be engineering versus maintenance. There is often much less engineering to do than maintenance.
I just don't believe that at all, performance and backwards compatibility has been trumping quality throughout it's development.
Even in C++, I always had bound checking on my own classes and always make use of the validation flags in VC++.
It never mattered to the type of applications I was involved with.
Firefox now uses it in release builds (for vector-like objects) for security reasons, and IIRC there was no real performance impact.
"Many years later we asked our customers whether they wished us to provide an option to switch off these checks in the interests of efficiency on production runs. Unanimously, they urged us not to--they already knew how frequently subscript errors occur on production runs where failure to detect them could be disastrous. I note with fear and horror that even in 1980, language designers and users have not learned this lesson. In any respectable branch of engineering, failure to observe such elementary precautions would have long been against the law."
-- C. A. R. Hoare, Turing award lecture in 1980, http://cacm.acm.org/magazines/1981/2/10949-the-emperors-old-...
We don't believe such a thing exists.
Our competitors do a bunch of code generation to accomplish the same things in Fortran that we do with templates and policy classes.
Sometimes, for shits and giggles, I'll prototype algorithms in Haskell or Common Lisp or what have you and, I have to say, the experience isn't really all that compelling, and this is without introducing MPI and all the associated headaches of working with MPI in something it doesn't support first-class.
I only use Fortran just for low-level number crunching, and I must say I have yet to miss C++ templates here for this kind of stuff. I'm curious, what is your typical use of templates in your simulation code?
Apart from templating over floating-point precision, we use templates and policy classes to do a lot of the code reuse / flow control you'd use run-time polymorphism for, but without the overhead of virtual function calls. This is pretty useful for us, because our simulation algorithm has a lot of sub-parts that can be done in different ways. Rather than having a bunch of switch statements (or virtual function calls) in inner loops, we can have that switch statement once, in a factory object, and return instances of objects templated over the correct policy class so that we don't have to branch in inner loops.
One of our main competitors is on the Fortran / Python plan. Our application has, instead, a few proprietary input formats (one XML-ish, and the other binary to be used with a GUI). This has its drawbacks (i.e. rolling and using our own Python-based macro language for use with the XML-ish input files). The CEO tells me, though, that this is actually kind of a godsend from a support perspective, because there is a point where all of the customer's simulation logic is frozen into a text file, which we can then debug (this is in contrast to the Python / Fortran approach, where the customer's simulation logic may be very tightly coupled with our own code).
Have you looked into a language like Julia or a framework like Charm++? I've seen these used in research papers, but I'm curious if these are used out in industry.
If you are looking for something like C++ in terms of performance and has a nicer syntax, you should try the D programming language. It's very nice to use, as fast as safe C++ code (you can write unsafe C++ that is faster), has stronger typing, templates, mixins, and can interface with C /C++ libraries.
I've moved my personal projects over to D, I've started writing a game with OpenGL, SDL, ASSIMP, Devil and it's much easier than C or C++.
Some links for those who are interested:
Main website: http://dlang.org/
Package manager: http://code.dlang.org/
Some interesting documentation pages:
Interfacing with C: http://dlang.org/spec/interfaceToC.html
Interfacing with C++: http://dlang.org/spec/cpp_interface.html
Templates: http://dlang.org/spec/template.html
Inline Assembler: http://dlang.org/spec/iasm.html
Status of various platforms: https://wiki.dlang.org/LDC
For instance using the json for modern c++ json parser, you can write this:
myclass c = json_node;
and it compile time statically checks that a json->myclass deserializer exists, and gives sane errors if one of the (recursive) subfields of myclass does not have a json deserializer.
This makes json processing in python look like blood letting, and is close (until runtime) to the experience I'd expect from ocaml and other functional languages.
But it robs a lot of much slower languages of their best value proposition. You can now do it all in C++ with correctness guarantees and still run 10x faster than most strong typed systems.
C++ isn't "good" or "bad", it's just OLD (and is backwards compatible with an even OLDER language).
We are continually learning which language abstractions give a lot of implementation leverage (e.g. garbage collection), and which introduce unnecessary complexity.
Any new(er) language has the benefit of incorporating those learnings into the language design.
Putting garbage collection in that basket is controversial and lately the evidence is piling up against it.
Notice how new important growing languages like Swift and Rust don't have garbage collection and programmers don't miss it. GC is more and more restricted to low performance languages like Python, Javascript, and Ruby and a few specialized highly tuned and expensively engineered exceptions like the JVM and obscure LISP engines.
And if you've ever tried to program responsive, interactive, predictable, or time-critical systems, you know that GC is ruinous and awful for those applications. Meanwhile languages like Rust, Swift, and C++ can be used for everything from systems programming to games to low power mobile apps to scripting.
Regarding responsive interfaces: pure reference counting is particularly problematic for this, because an unbounded amount of work may happen every time an object's reference is decremented (because the object might be freed, which causes other objects' references to become zero, etc). If this happens inside a critical section Your Life Is Pain. At least you can control when this happens by taking and then dropping an additional reference. (See Obj-C's allocation pools.)
C++'s shared_ptr<>, BTW, is also reference counting, and suffers from the same problem. So it's technically correct (which is the best kind of correct) to say that C++ has garbage collection too.
You can twist words and say that shared_ptr means C++ has 'garbage collection' but I doubt anyone would agree with you if were were to word it like:
"C++ has a garbage collector"
Ref counting is a form of 'garbage collection' in so far as it is a way to release memory, that's about it. I certainly wouldn't consider Rust's Arc<T> a 'opt in garbage collector'.
It's true that there can be unlimited work done in reference counting. Of course, it's true there can be unlimited work in any function of any program. [0] With reference counting a programmer can fix the amount of work to be done and when in deterministic fashion. With garbage collection, there is no such power. The gc decides when it will work and you cannot control or predict the interruption.
You cannot produce serious interactive or time sensitive control software like that. You certainly can't write system software like that.
Swift is using reference counting which is a form of garbage collection.
Or (hahahah!) Symbian C++?
Ah, I see, you meant C++11-without-thread_local-because-CUDA-requires-an-older-XCode. Got it!
More seriously, the large enough Noto Sans font with a hint of extra weight renders so gorgeous in Firefox (it's even bearable in Chrome!). I wish all webpages were as readable.
As for the content, well, going back to: https://eklitzke.org/c++-java-go-and-rust I think the problem of the author is that he doesn't realize it's possible to do much better than C++. Claiming Rusts' ownership and borrow checking is exactly equivalent to std::unique_ptr or that Rusts' concurrency support is comparable to std::thread betrays very deep nativity, misunderstanding or just a mindset that can't see beyond what C++ offers.
It is also essentially impossible to know that your code is well-tested: even when using something large and well-known like Boost, its authors cannot know what will happen when you substitute in 4 of your own types (my bet is “result not quite working as intended; obscure bugs added”).
I use templates but I am quite aware of code complexity and I essentially stop when the templating goes too far.
Somewhere along the line, we seem to have gotten into a mode of wanting generic code at all costs. Why? It is just fine to expose a few common specific methods when those are very helpful and clear (such as classes exposing a “string value”, “integer value” and “float value” instead of trying to provide some single partially-specialized template mess of a method that manages to still not quite work right in every scenario).
I know. Years ago I proposed a vector library for 2, 3, and 4 element vectors [1] as a standard. The immediate complaint was that it didn't use templates.
I don't blame glm for picking the latter. Every option is painful, but templates might be a little less so.
One of the projects I'm working on could have just as easily been written in c++ instead of go.. except that in go starting the project and building it involved
mkdir my_project
# hack
go build
I wouldn't even know where to start to write a simple c++ server that uses zmq and slings json around. How am I supposed to handle dependencies and vendoring?As much of a PITA it is trying to learn rust, getting the toolchain working and starting a new project was not one of the issues I ran into.
That's a start for what you want.
https://www.amazon.com/Effective-Modern-Specific-Ways-Improv...
cmake is pretty awesome at handling dependencies; our build process grabs dependencies from git and adds them to the project. Yes, there is more overhead and a learning curve, and if you are running a simple server there are probably better choices; we use a ton of python for these things, and wrap performant code in cython.
OK... Now how do you turn those 30 lines of code into an actual project that you can build and cross compile? Write 100 lines of cmake stuff to build 30 lines of code?
I think if I was starting from scratch I'd try to use something like bazel.
Anyway, the author later says he just enjoys writing low-level C++ code, however unpractical this may be. In which case I don't really see the point of defending his choice.
This doesn't make sense to me. That 15% of time is spent somewhere. It certainly isn't just "ambient".
Most of the fast binary parts of templates is from stuff like specialization, which can be added to just about any generics system. Rust and Haskell both have it.
The templating system in C++ is not generic type system, it's not even strictly speaking part of the C++ type system. It's usually define as a metaprogramming facility. Because it be used to abstract on types, it's the defacto generic system in C++, but it can also be used to abstract over definitions, expressions, computation shapes (like unrolling a loop on a factor relative to the size of a type). C++ templates are slow when compared to other generic system because of a lot of bad design decisions (compilation model and how/when a template has to be intanciated), but also because it can do more, and is used to do more.
> the compiler can use knowledge of specific type classes, interfaces, modules to optimize the implementation of.
Depends on what you mean by more information: In c++ complex type constraints can be express through template. Even more important, in you example you have to rely on someone in the rust compiler community to implement that specific type transformation. Because, the template system is extremely expressive,whoever designed the "option type" can also ship instructions to the compiler on how to specialize for NonZero type...
> You can also have nice features like GHC's rewrite rules which allow you to effectively tell the compiler how to optimize your types.
It's hard to have both, most generic type system are fast because they don't do much as you start adding feature and smartness into the system, the performance degrades...scala compile time being a good example.
> Rust and Haskell both have it. can you specialize on struct in rust/haskell or just implementation of traits ?
C++ templates, in essence, are rewrite rules. And they can be used to optimize types.
You can replace C++ with <insert language here> and you can replace "language" with entire programming stacks. Large numbers of programming software toolsmiths have been laboring towards the wrong goals for the past few decades. We programmers are like old school computer hardware manufacturers hell-bent on delivering the highest spec numbers at the highest margins, while consumers were beset with poor quality, poor reliability, and experience degrading bloatware.
We programmers are particularly prone to inflicting ourselves with experience degrading bloatware, while ignoring our own particular human interface design needs. We need to stop emphasizing "sexy" things like raw performance and mathematically provable semantic guarantees and start looking at how we impact our experience while reading and debugging code. We need to start calling out toolsmiths who give us "power" at the cost of long startup penalties, and unresponsive, unwieldy software tools.
> but many C++ programmers disable exceptions for performance
I have never seen a project like this for 10+something years. The only piece of code with disabled exceptions that I've seen was created for Atmel controllers. And in modern C++ exceptions is zero-cost. Your paying for exceptions only when they occur so, nobody is disabling exceptions now.
This is not the only line that bugs me but I don't have enough time for it right now.
> On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions.
And most importantly, I don't think that they're disabling exceptions using compiler flag. I'm sure that they just using error codes for error handling instead of exceptions.
Embedded people still disable exceptions.
I don't understand this statement at all. C is a much weaker type system than C++. You can do things in C that will never compile in C++, it is much, much stricter.
This is one of the reasons why Andrew Sutton and Bjarne Stroustrup are trying to push C++ Concepts since C++11 [1]. They should provide much easier to understand compile time errors when it comes to templates.
I believe there is some thought being put into making a C++ package standard [0], which would do wonders for the language. in my opinion half of the reason Node took off is because npm is so easy to use, and people are getting excited about Rust partially because Cargo is so well thought out. Now I might be wrong here, but I think if you took modern C++ (no raw pointer manipulation) and combined it with a good package manager, I think you would pretty much erase any advantages Rust offers.
[0]: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p023...
I've seen this opinion now twice in short succession on HN. Issues with C++ safety aren't just a matter of a dangling pointer that should've been a unique_ptr or shared_ptr. It's massively naive to think that this would in any way be comparable to Rust.
That's not even considering the reality that no real-life C++ codebase seems to survive on those modern C++ features alone. (If it did, I presume Mozilla would've rewritten Firefox in C++11/14/17 instead of Rust. Oh wait, they already use C++11...)
While I agree, I would point out that in the same way that "safe" Rust is a usable (if difficult to get used to) subset of "unsafe" Rust, there also exist usable safe subsets of C++ [1]. Tooling to enforce that Rust code strictly conform to the safe subset, of course, already exists (and is built into the compiler). Such enforcement tools do not yet exist for C++ code, but I think they're coming. And I think they'll probably support safe subsets that are more convenient/intuitive/easier-to-use than (the current version of) safe Rust.
I wonder if adopting Rust to avoid the pervasive unsafe code in C++ isn't a little bit akin to adopting Esperanto to avoid the pervasive cursing in English. I mean, there does exist a non-vulgar subset of the English language, even if it's difficult to persuade people to stick to it :) But then, if all the cool kids are talking Esperanto...
> (If it did, I presume Mozilla would've rewritten Firefox in C++11/14/17 instead of Rust. Oh wait, they already use C++11...)
I think this may be a missed opportunity by the Firefox developers. If you look at the code, they're still using new/delete and raw pointers targeting dynamic objects. I presume that a lot the code has survived from the pre-C++11 era. I think converting their code to a safe subset of C++ (like SaferCPlusPlus) would be quicker and require less effort than a rewrite in Rust.
[1] for example (shameless plug): https://github.com/duneroadrunner/SaferCPlusPlus
Where did you get this idea that "safe" Rust is a subset of "unsafe" Rust? Your whole premise here perhaps qualifies as not even wrong: this is not how safety in Rust is conceived or conceptualized.
I think you are exaggerating. Most projects with any user base provide ready binaries which able to get going pretty fast.
"it's so bad that big C++ projects like Firefox and Chromium basically write their own scripts that download and build dependencies, and simply commit the source code of the libraries they use directly into their own tree."
I would not call this 'bad' but resilient.
"Replicating is bad" is a non value adding rule of thumb, imo.
That said, yes, it's very hard to start incorporating third party libraries to C++ when compared to any other language.
But hey, modules are coming in the next couple years. Should really help with this.
But what about the dependencies of those binaries/libraries? Manually playing that cat and mouse game just sucks.
This is both a blessing and a curse. As a blessing, it leads to very neat, clean, APIs and you never have to worry about such template expansion errors. As a curse, some of the more complex bits of C++ metaprogramming (check out what people achieve with SFINAE) are not possible. I personally think the pros outweigh the cons, but many people from the C++ world really like the power of template metaprogramming in C++. Rust is planning on offering procedural macros which address some of the use cases, but not all.
Other than metaprogramming, Rust's implementation can provide the same functionality that templates do, in a cleaner way in my view.
It also depends a bit on why you like Visual Studio. Because it has one of the best Intellisense implementations? Much more common outside Visual Studio for languages that are not C++... Good visual debugger? etc...
I am not so sure about that. C++ support in VS is rather terrible - especially when compared with support of C#. For C#, VS is excellent.
You may be thinking of the lack of full C99 support.
More here: http://joearms.github.io/2013/03/28/solving-the-wrong-proble...
2) Programmer time is (usually) more costly than anything else in your organization. I'd argue that for most organizations, they're not making enough money per unit of throughput to justify the excessive programming time.
3) C++ is not designed for operators. Rust has this problem too. Once you know how to inspect a Java, Erlang, or Go program, the tools become familiar.
Sometimes throwing hardware at problems don’t work. Either because it’s technically impossible (console games, mobile) or because you don’t own the hardware (PC games, desktop software). For such products, either you spent “excessive programming time” programming C++, or you won’t release any product at all.
You have plenty of performance with C, and C++ is what you get when you enforce C compatibility at all costs, then tack on other stuff. The memory layout that classes and class hierarchies force upon you lead to sub-optimal caching behavior. Virtual functions don't have optimal performance, but they still made the cut. Pointer aliasing actually hurts performance as it prevents the compiler from doing optimizations.
I do agree with everything that was said in "The Joy Of C++", bonus points for acknowledging the Stockholm syndrome. However, pretty much all of it could be said about C.
Simple classes have the same memory layout as C structs, contiguous chunk of memory which means they are cache friendly.
Really? Template metaprogramming is not the only use valid use of templates. Most time a simple <class T> is enough and that is already a huge improvement over C.
Like say you have a collection of entities where each entity can have one or more components of different types. Now you want to find all entities with components A, B, C and the returned value should have typed references to components - it gets a bit hairy to implement but it's trivial to use and efficient.
Sounds like the beginning of a story, during which you explain the advantages and disadvantages, determine where C++ is best used, and compare it to other options.
Finally would likely just encourage people to write really awful C++ code.
(also I totally disagree that RAII is superior to finally. Finally, being lexically scoped, is far simpler, far shorter and far easier to understand. https://codecraft.co/2013/10/31/why-we-need-try-finally-not-... )
I do not know if anyone has proposed it for C++, but I would be surprised if it passed given that it doesn't accomplish much.
Here’s my blog post about that: http://const.me/articles/why-cpp/
Copy-elision: the copy constructor is unneeded, we should be move by default.
Answer: Rust.
I don't know why so many languages support lambda nowadays. It looks so weird and unnatural.
I still have to use c++ in some projects, never for the new syntaxes, just for there are some libraries I must use.
1. Defining a function within a function.
2. Capturing a function call for later use.
It give me the feeling that, c++ gives every corner a special syntax, or c++ adds new features by adding new syntaxes, there is no the word "reuse" in the process of improving c++.
In go, anonymous functions and general functions and methods have no much differences. But in c++, lambda and general functions and class methods are too different. Using class methods as callback in c++ is awful.
C++1x features make c++ code less readable, for fewer and fewer programmers know every syntax corners in c++.
I would use it for something like the Unreal game engine, because I know that:
- performance is important in much of the project
- the problem is complex enough to require high level language constructs
But for most tasks, my time would be better spent using a high-level language and then optimising the hot spots in, say, C.
At scale this always becomes true. C++ can be written with reference counting and other high level concepts with runtime penalties. When you need to optimize or scale, you will never need to look to another language. I do a lot of numerical computing in Python and often need to drop into Cython or C; in C++ this wouldn't need to happen. One the the main goals of C++ is that "there is no language below C++".
High level language constructs are always nice, and C++ has a lot of "zero-cost" abstractions, meaning you only pay for what you need. For example, an iterator in C++ can just be a raw pointer in the case of iterating over a vector, but it is more complicated for a std::map because it is backed by a tree. C++ is a high-level language, so I don't understand the argument that you would be better off splitting your stack between the "important" parts and the slow parts.
We could make that sentence damning or glorifying, depending on the missing word choice and someone would argue with you about it, no matter what word.
There are plenty of reasons not to use C++ or Rust. They are not magic bullets which solve all engineering challenges.