18 ms·
Does C++ still deserve a bad rap?
- mehrdadn 6y agoI say this with a lot of love for C++, and I think it has gotten much better, but just try splitting a string via another string as the delimiter...
- CyberDildonics 6y agoWhy would that be more difficult in C++?
- mehrdadn 6y agoBecause it doesn't even exist as provided functionality; you have to code basic stuff like this yourself. See for example https://stackoverflow.com/a/14267455 https://stackoverflow.com/a/14267455
- kenniskrag 6y agoIt is possible with a regex iterator #include <iostream> #include <regex> #include <string> int main() { std::string s = "Python*C++*Java"; std::regex regex("\\*"); std::vector<std::string> out(std::sregex_token_iterator(s.begin(), s.end(), regex, -1), std::sregex_token_iterator()); for (auto &s: out) { std::cout << s << '\n'; } return 0; }
- mraza007 6y agoHey just curious i have only coded c++ in school I’m curious to know why don’t we use `using namespace std;` in real world when writing c++
- saagarjha 6y agoBecause it imports literally everything into your current scope, and the standard library types are named in such a way that they will likely conflict with code you write. Named a variable “min” or “max”? Function called “list”? You’re going to cause problems for yourself. Plus, using std:: is generally a good reminder that you’re using the standard library types and not some homegrown facsimile of that type, as is common in many C++ projects.
- jdrek1 6y agoBecause it imports everything from the std namespace and can lead to name clashes. It also makes it harder to see where symbols come from. If you see `std::vector` you know exactly what it is. If you just see `vector` in a large code base it could be anything. Could be a hand-rolled version of std::vector from prehistoric times or people not trusting the STL for no reason. Could also be a mathematical vector or something for vector graphics or whatever else. That is why people generally always fully specify where things come from, it's not limited to just the STL. `using namespace X;` is somewhat fine if you limit it to a scope by using it in a source file and ideally only the function body where you use it, in header files it is a really bad idea because then the namespace gets exposed to everything including that header. That can lead to the compiler calling the wrong function and you might not even notice it.
- mehrdadn 6y agoIn addition to the other comments (which are the primary reasons), beware that you can actually get different behavior due to something called "argument-dependent lookup". The most well-known example being std::swap(a, b). In general it is not equivalent to using namespace std; swap(a, b), though in this case, you actually want to say something else (using std::swap; swap(a, b)) to avoid importing the entire std namespace while also ensuring you call the ADL version of swap that may have been provided.
- secondcoming 6y agoStop
- kingaillas 6y agoThis is my annoyance with C++, it feels like the effort put into the language is disproportionate. As in, the committee is off solving problems that a handful of library implementors will use, but basic things like splitting strings or trimming whitespace is ignored. Yes these are fairly trivial but you either roll them over and over or start carrying around a little utility library.
- 0-_-0 6y agoAfter having used both Python and C++ for a while I concluded that most of the problems of C++ could be solved by a proper standard library.
- jcelerier 6y agoBeh, it's one function call if you use Qt or boost
- valbaca 6y agoDifficult, probably not. Verbose and clunky and needs a web search to do, yes. I'm guessing it's analogous to Java's Regex. Like, yes, they're there and do as much as any other language, but lord it's a PITA.
- seppel 6y agoIt is not difficult to do it, but it is difficult to do right and in a C++ way. That means with least overhead, i.e. not copying stuff if not necessary and not doing any memory allocations. This is why C++ still has no string split is its standard libary: People cannot agree how it should look like. There is, however, boost::split from the famous boost library.
- mehrdadn 6y agoDo you know if they're revisited this ever since string_view was implemented? I feel like a vector<string_view> should be quite uncontroversial, and you could even propagate the allocator from the string to the vector.
- seppel 6y agoSince they now have ranges, the discussion can start all over... But I'm maybe no completely up to date, where the discussions is.
- makapuf 6y agoWith range it would be auto splitText = text | view::split(' ') | ranges::to<std::vector<std::<wbr />string>>();
- deleted 6y ago[deleted]
- leni536 6y agoIt should return a range of string views, no allocation is necessary.
- mehrdadn 6y agoThat sounds like a great idea. Not sure if it might present a bit of a hurdle if the caller prefers it to be random-access, but I'm kind of tempted to try this out and see if it might present issues in practice. It might be worth suggesting it to the standards committee?
- oscargrouch 6y agoIs there any language where string handling doesn't suck? (No script languages please, because they cheat by implementing the hard things on C or C++) From memory the less horrible experience i had was with Go, but there's help for the slices on the runtime which let the difficult parts hidden and also the batteries-included std library, which is one of the most well designed standard libraries out there. Buffer management is one of the things that sucks the most in any language, and the ones that dont its because the complexity is hidden in another fundamental layer.
- philipkglass 6y agoI think it's pretty nice in Scala. I don't know if "no virtual machines" was implied as part of the "no script languages" request, though. scala> "Mary had a little lamb. The lamb was in federal witness protection.".split("lamb") res0: Array[String] = Array("Mary had a little ", ". The ", " was in federal witness protection.")
- oscargrouch 6y agoNo, its ok and not part of that category. I meant for languages where the hard parts are delegated to another like Python and Javascript (C and C++ respectively).
- mehrdadn 6y agoC# and Python... "a, b".Split(", ") // C# "a, b".split(", ") # Python
- Measter 6y agoIn Rust: "a, b".split(", ")
- sasaf5 6y agoI would risk to mention Tcl as a good candidate, which might be unfair because the language is designed for strings. split "foo.bar" . => foo bar
- 6y ago
- 29athrowaway 6y agoIn C++ you can implement it in a way that gives you much more control. Do you want to truncate the string? return new strings? return string views? It all depends what you need. In some languages all strings are immutable and all operations result in new strings and you have no control over that.
- mehrdadn 6y agoThe trouble is often it doesn't matter and literally any of those would be useful, and yet none of them exists for you to use, so you have to waste time reinventing the wheel.
- 29athrowaway 6y agoPerhaps they're not in the standard library, but they're readily available on Boost, POCO and many other well known mature libraries. Check the Boost C++ string algorithms library. https://www.boost.org/doc/libs/1_74_0/doc/html/string_algo/usage.html#id-1.3.3.5.9 https://www.boost.org/doc/libs/1_74_0/doc/html/string_algo/u...
- jeffbee 6y agoMy favorite weapon of choice for this is absl::StrSplit. It can be very efficient because it adapts to any return type you like (including range types, so you can `for(string_view : StrSplit()) {...}`).
- spaetzleesser 6y agoTo be fair this is not a problem of the language but a library problem.
- creato 6y agoI don't think C++ ever really had a bad rap except among ideologues and evangelists of other languages. In my experience, people like this are very rare in the real world outside of maybe Rust conferences.
- deleted 6y ago[deleted]
- mcqueenjordan 6y agoYour experience is highly incongruent with mine. I work with a lot of Rustaceans, and while they're often able to articulate why they prefer Rust over C++ for many applications, many of them would probably be reaching for C++ if not for Rust, and certainly don't spend time hating on the language. Speaking personally as a Rust fanatic, C++ is still my 3rd favorite language. (Out of a large N.) I guess my point is, this is a weird (and IMO, flat-out wrong) dig at the Rust community.
- mhh__ 6y agoEqually, a lot of people just don't know any different. How would you know C++ isn't optimal if you've never tried or thought about anything else. That and the sunk-cost of learning C++ is large.
- Darvon 6y agoYou can't get a degree without being exposed to a number of lecturer's language-of-choice. I'd be shocked to find someone who had only used c++
- mhh__ 6y agoLecturers are often fairly poor programmers, which is sort of within the point I was making. You might learn Java and C++ but you'll probably be writing one in the other no matter what you do first. I.e. my current lecturer in C programming seemed to imply we were going to be learning about object oriented programming in plain C (specifically inheritance), which does not bode well if he didn't misspeek
- topspin 6y agoDepends: does it still have header files?
- BenFrantzDale 6y agoHopefully not, with modules in C++20 and beyond. Of course, it still will support headers.
- randyrand 6y agofor people that dont like headers, how do you browse the api of a class? Scrolling through the implementation?
- wilsonthewhale 6y agoa proper, standardized documentation system like godoc and rustdoc
- randyrand 6y agoI'm down for that, but many languages without headers don't have that by default.
- uryga 6y agoi look at a nice HTML documentation page generated from the code. happily, no one has to maintain that by hand :) i like how haskell does it: https://hackage.haskell.org/package/base-4.14.0.0/docs/Data-List.html https://hackage.haskell.org/package/base-4.14.0.0/docs/Data-...
- skocznymroczny 6y agoYou write the name of the class, add a dot and press ctrl+space
- pornel 6y agoIn Rust it's solved by `cargo doc` and https://docs.rs https://docs.rs
- flowerlad 6y agoC++ is a very poorly designed language. A lot of the work being done by the committees is fixing Stroustrup's mistakes. Consider horrors such as this. In the following statement what are foo and bar? int x = foo(2) + bar(3); Most people will say foo and bar are functions and that's a reasonable guess. Unless you are talking about C++. In C++ foo and bar could be functions but could also lots of other things. For example it could be the equivalent of the statement below: int x = (foo)2 + (bar)3; In other words type casting can be written as (foo)2 or as foo(2). Just to make it harder to understand what is going on. As another example consider implicit type conversions: Foo b = c + 3; If 3 is not compatible with whatever type c is then C++ checks if there is a constructor that accepts an int parameter, and it automatically calls the constructor to convert 3 to the appropriate type. Many of these craziness is being addressed by standards committees. C++ as designed by Stroustrup is a horrible language. Just look at his C++ book. It is huge and heavy and in fact Stroustrup takes pride in how big and complex the language is. C is an awesome language. C++ is horrible.
- api 6y agoThis weird ambiguous syntax exists to allow among other things templates that take either primitive or class types. It makes primitive types usable as if they are classes with copy constructors. That being said, it can certainly be ugly. A lot of the ugliness comes from trying to maintain itself as a mostly superset of C. Technically it no longer is strictly that, but most C code will compile fine in a C++ source file.
- pmoriarty 6y ago"Most people will say foo and bar are functions and that's a reasonable guess. Unless you are talking about C++. In C++ foo and bar could be functions but could also lots of other things." Same as in Lisp, one of the most beloved of languages on HN. Were Lisp's macros a mistake? Some will say yes, but overall the language is more praised for them than damned. So highly regarded are Lisp macros that many languages will eagerly proclaim that they have macros too -- even if they're not homoiconic and so harder to work with than in Lisp. Few if any are the languages that proudly proclaim that they don't have macros because they thought Lisp macros were a big mistake. C++ fans themselves often point out that C++ templates can be as powerful as Lisp macros. So which is it? Is giving users the power to radically transform their language a bug or a feature?
- _wldu 6y agoC++ will be around for at least the next 100 years. It's an ISO standard used by business and government all over the world. Modern C++ is very safe and fast too.
- oscargrouch 6y ago35 min of this statement and nobody to tell us of why, we, the C++ sinners, must convert to Rust or face the damnation in the hell of eternal unsafety and infinite bugs. It must be some kind of HN record.
- unnouinceput 6y ago100 years is a long time in technology. A safer bet would be to say "Assembler will be around in a 100 years". High level languages tend to get replaced after a while.
- _wldu 6y agoC++ has already been around for 36 years.
- unnouinceput 6y agoAnd COBOL was for ~40 years before starting to be left in oblivion in 2000's. Your point?
- deleted 6y ago[deleted]
- jroesch 6y agoTLDR Yes. I having been writing C++ extensively for research/work/etc the past 5 years. Compared with modern languages it completely deserves the bad rap. C++ has come a long way, can you write cleaner code than you could 10 years ago? yes. Are there safer abstractions than there were? yes. The amount of issues I have to deal with in C++ on a day to day basis which are just non-issues in Rust or Go, etc. Without complaining too much dependency management and tooling are stuck in the stone age. Every time I get to use Cargo going back to C++ is a nightmare, even Python which has pretty poor tooling around this is a million light years ahead. Even simple things like having to carefully order headers or deal with obscure cross-platform incompatibility are mostly non-issues in newer languages and the baggage of C and C++ leads to a lot of unnecessary pain that doesn't provide low-level control or performance advantages.
- HexDecOctBin 6y agoRight at the beginning, > This calls for regular expressions Why? A regular expression is a whole new program, written in a whole new programming language (one used to program finite state machines, instead of Turing ones, but still). Why not just write a simple function to compare string suffix? Is you programming language (C++, in this case) so anaemic that you need a whole different language to do such basic operations? This is what people who don't like C++ complain about, in addition to the language, the self-indulgent culture around it.
- tialaramex 6y agoThat immediately jumped out at me. They don't need a regular expression here, it's probably an inappropriate fit, or else it's revealing an undisclosed design assumption. It certainly ensures that I don't take their conclusion to be worth much.
- reanimus 6y agoI mean, there's https://en.cppreference.com/w/cpp/string/basic_string/ends_with https://en.cppreference.com/w/cpp/string/basic_string/ends_w... lol
- jimbob45 6y agoThe current state of C++ is that of Madonna trying to stay relevant in the modern music world. You can have her rap, have her dab, or use autotune but she still won’t fit in as easily as a Billie Eilish. I look at C++ and wish it had C#’s compile-time attributes, first-class reflection, mixins, a decent syntax for pure virtual functions, and a more logical pointer syntax (it’s illogical and you know it). However, they can’t give me those things without drastically breaking backwards compatibility. At that point it’s a new language. I wish we could just develop a C++ 2 for greenfield projects and stop development of C++ where it’s at instead of Frankensteining more features onto it. I guess that’s what Nim and Rust are for.
- lionkor 6y agothose are super weird things to ask from C++, except the reflection. More logical pointer syntax? How is int* -> pointer to int and &abc -> address of abc and abc->xyz -> pointer access to xyz field and *abc -> dereference not as easy as it gets? 4 operators for 4 different things - whats the issue?
- notacoward 6y agoThe author concludes "it would seem to be fairly nice" but ... compared to what? Without comparing to a solution in at least one modern alternative, I'm not sure the statement means anything at all.
- flubert 6y agoIs this a nerd sniping thing? It has been a while since I've wrestled with Perl, but I suppose the recursive file search would keep it from being a one-liner. 4-5 "reasonable" lines maybe? Definitely less than 80 characters? I see I don't even have Perl installed on this machine, oh well.
- jeffbee 6y agoIt does seem like a weird choice, since anyone faced with this problem fewer than a billion times will surely choose shell tools. In python it's pretty short, and I don't even know python. from collections import defaultdict ...: d=defaultdict(int) ...: for fn in glob.iglob("**/*.txt"): ...: with open(fn, 'r') as f: ...: for line in f: ...: for word in line.split(): ...: d[word] = d[word] + 1 ...: [(k, v) for k, v in sorted(d.items(), key=lambda x: x[1], reverse=True)][:10] That said, the C++ version in the article could be tightened up a bit. What's happening on line 34, for instance?
- tzs 6y agoI'd probably just do it with existing commands (pipe split across multiple lines to make it easier to read): find . -type f -name '*.txt' -print0 | xargs -0 cat | tr ' \t' '\n\n' | grep '\S' | sort | uniq -c | sort -nr | sed 10q I'm assuming that when it says find all the .txt files in subdirectories of the current directory, that should include .txt files in the current directory.
- john_moscow 6y agoLike every programming language out there, C++ is a tool. And like every tool out there it has its uses. There isn't any point of using C++ to count words in a text file. Any high-level language like Python will beat you to it. However, there's one thing you can do in C++ and not in Python or JavaScript or PHP: fully control the memory layout of your data. While you don't need it in most of the cases, it becomes a killer feature when directly dealing with large amounts of data: * Try implementing an on-disk hash table in Python and you're stuck manually packing ints and longs in an out of arrays. In C++ it could a simple template used with a memory-mapped file. * Try doing anything non-trivial on a microcontroller with 32KB of RAM. You could theoretically use a higher-level language, but you will end up using >10x amount of RAM. * Try designing an application-specific data structure in any other language. Let's say you have an ~8GB in-memory database that slowly adds records one-by-one and then invalidates them in chunks. A C++ implementation will rip anything else to shreds. You just won't get the same speed and memory efficiency. What it means in practice, is that unless you have an existing project that uses C++ anyway, you want to partition it: do the memory-critical part in C++, and communicate to it from a higher-level language via a high-level interface. You will get performance where you need it and a peace of mind everywhere else.
- wirthjason 6y ago> There isn't any point of using C++ to count words in a text file. Any high-level language like Python will beat you to it. However, there's one thing you can do in C++ and not in Python or JavaScript or PHP: fully control the memory layout of your data. Any books or resources for digging deeper in these kinds of topics? I’m a Python developer and would like to learn C++ but the just the reasons you mentioned make it hard to leave Python.
- danudey 6y agoyou can malloc() to get a memory range, or mmap() to get a disk-backed memory range with kernel-managed paging, and then you can do whatever you want with it. You get a pointer to the start of the range, and you know how large it is, so from there it's just pointer arithmetic and assignment. Easy peasy. Now you just have to make sure that you zero data when you're done with it, track how much of that memory is available or used (and which sections), and (optionally) implement your own defragmentation and garbage collection. Unless you desperately need to specifically manage the memory layout of your data (e.g. for alignment purposes for massive data processing), none of this is worth the time or trouble to do for most projects, not only because it's a huge amount of work for little gain, but because you'll almost definitely screw it up and potentially corrupt your entire data set. Note that, at least for the on-disk hashmap set, you absolutely can do this in python, so if you're interested in experimenting with this sort of data management, practice it there first. A good place to start: https://github.com/luispedro/diskhash https://github.com/luispedro/diskhash
- giancarlostoro 6y agoI think you could argue every single programming language has a bad reputation under any context. Name a single programming language and someone will have something bad to say about it. I think C# is fantastic, and I bet someone, somewhere will thrash on it despite it being quite a powerful and rich language. Heck, I can pick on things about C# I don't like, but fortunately they seem to be aiming towards partially addressing those. I think C++ is not inherently completely bad, the usual thing is "do it the right way" which is usually some spec the community has drafted up with arguments why certain styles or code decisions are bad and what their better alternatives are and why. In the face of Python we have PEP-8 for example. C++ makes it easy to shoot yourself in the foot with a shotgun, and that means you need to think a little more about your approach and ensure you know what you're doing to begin with.
- hoytech 6y agoNeeds more shell, less egg: https://leancrew.com/all-this/2011/12/more-shell-less-egg/ https://leancrew.com/all-this/2011/12/more-shell-less-egg/
- jjgreen 6y agoFabulous, thank you.
- zests 6y agoI'm not a fan of the syntax. I've never used C++ but it just looks arcane to me. Its hard to imagine enjoying programming with such a syntax heavy language. Anyway, here is my bash version of the problem. Now that WSL is distributed with windows, does it also hit the "runs on all major platforms with no dependencies" mark? For the record, this hits the enjoyment mark 100%. cat $(find . -name "*.txt" | xargs) | tr ' ' '\n' | sort | uniq -c | sort -k1 -n -r | grep -E '^\d+ [[:alpha:]]+$' | head -n 10
- jarjoura 6y agoSo first, C++ in a small codebase with a small team, is a very powerful language that really does produce the best code. That's what you want in a professional, top tier code base and that's what you get. Unfortunately, once a project grows to many developers, many of whom have varying levels of experience, it's just too easy to write bad C++ that becomes impossible to debug. I've been using it for a decade and I swear I barely scratch the surface of its features. Lastly, and this one is the most annoying, C++ also has cryptic error messages that almost always never mean what they suggest. You'll learn to understand them over time and decode their meanings, but at first glance you'll spend long days hunting for the wrong issue.
- msla 6y ago> So first, C++ in a small codebase with a small team, is a very powerful language that really does produce the best code. "Best" is such an undefined term it's word-noise here. "Best" in terms of end-user extensibility? "Best" in terms of debuggability? "Best" in terms of having a single binary which can be copied and run without regard for machine architecture and OS?
- secondcoming 6y agoIt's quite obvious that the poster was referring to codegen.
- msla 6y agoOf course not.
- deeringc 6y agoC++ error messages have been gradually improving over time. Clang really raised the bar when it came along, and the other two compilers have been catching up. Concepts in C++20 will really help to further improve things for template errors.
- jnxx 6y ago> So first, C++ in a small codebase with a small team, is a very powerful language that really does produce the best code. Does it? https://benchmarksgame-team.pages.debian.net/benchmarksgame/fastest/rust-gpp.html https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
- usefulcat 6y ago“There are only two kinds of languages: the ones people complain about and the ones nobody uses.” Bjarne Stroustrup
- ku-man 6y agoI don't hear too many complaints from C users. Perhaps because C never overpromised? I understand C++ is messy because, back in the day, Stroustrup never say no to a request or suggestion from a potential user. He wanted his language to be widely used. Guess he succeeded.
- roca 6y agoUnfortunately that quote is an all-purpose way to dismiss the volume of complaints about any language.
- umanwizard 6y agoRust is pretty widely used and in my (biased fanboy) opinion, strictly better than C++ in almost every way. (Not quite _every_ way: lack of per-container allocators, and less advanced generic/metaprogramming facilities are two particular pain points)
- btilly 6y agoIf this is the best that can be said for it, then yes. 60 lines of "portable code" turns out not to be portable. Practically every line requires some piece of C++ ceremony. The nightmares around the potential for "undefined behavior" and miscompilations of code by C++ are ignored. It has always been the case that there are several subsets of C++ which make reasonable languages. The problem is that when you combine them in the wrong way, you get into a world of hurt. And in the real world, C++ programmers do not agree on which subset to use.
- jnxx 6y agoWhat I am often wondering is why these subsets are not named, while it would increase clearness of communication and what is wanted and needed.
- jeffbee 6y agoA bad rap is, by definition, undeserved.
- DontGiveTwoFlux 6y agoAs someone who writes <5 commits of C++ per year, it is very frustrating. I can’t get through a code review without reviewers referencing at least 2 blog posts about proper style for modern C++. I’m sure if I were an expert who used it every day I could remember all the gotchas and best practices, but it sure is tedious to deal with occasionally. Too many foot guns and conventions, not enough constraints in the language.
- justicezyx 6y ago> <5 commits of C++ per year, I am sure any such developer will get equal treatment from another who is an expert, right?
- mehrdadn 6y agoA lot of this comes down to expectations. I would treat C++ like, say, kind of like a cabinet full of chemicals, rather than like (say) a typical home toolbox. You (hopefully) don't just grab containers and mix their chemicals and expect to learn by doing that 5 times a year; you really need to start slowly and take time to learn all the dangerous pitfalls properly, or otherwise expect to be told exactly what to do down to the most minute details. Adequate training for it is simply a prerequisite. C++ is kind of similar in that respect.
- emerged 6y agoI'm sorry but why would you expect anything different from a language you rarely use? I've picked up Python the past few years and have come to love it, but I'm sure any seasoned vet would eviscerate me in a code review.
- mrmonkeyman 6y agoThe point is, doing it "wrong" in Python means jack shit. In C++ kittens die, in Python you get some upset "vets" but nothing fundamental.
- machiaweliczny 6y agoSo C++ doesn't have linters? Why not configure the subset acceptable.
- llbowers 6y agoC++ is, quite rightly, considered an overly-complex and bloated language. A lot of newer features are papering over poor design from the beginnings of the language. But.. There is something about the use of destructors, RAII, and even smart-pointers that just feels so...elegant? I'm not sure what the word is I'm looking for. I feel like there's a kernel of a beautiful language hiding in c++ and those features are the integral parts of that.
- janselman 6y agoBecause C++ has almost all the possible features of the programming languages, so you find a subset to like in it. A language shines when it picks the correct subset of the features, not all.
- unrealhoang 6y agoRust does a good job capturing that kernel.
- oscargrouch 6y agoAny software where you will need to develop serious things for will suck. Almost nobody feels miserable in languages like python because they rarely have to deal with the ugly stuff or having people depending their lives on it. Thats the 50% of the fun writing in it, because you will deal mostly with the cool things, and who would not like the language that gives you that kind of pleasure? And the languages that are used for this kind of stuff will suck somehow, because its hard to make things right on them, it requires a lot of discipline and you will have to deal with big codebases, in big teams.. so the things gets much harder to do right. The guy that is chearing Rust today, is the guy that will complain 10 years from now, how Rust sucks, because he have to deal with it everyday in its big avionics codebase and any mistake can cost million of dollars or peoples lives. Its psychology. We need the shiny new thing to give more meaning to our lives. It will never stop, but with time you learn to navigate over it a little better. There is very little change in languages now, and once someone does a real paradigm shift, it will be impossible to ignore.
- tluyben2 6y ago> The guy that is cheering Rust today, is the guy that will complain 10 years from now, how Rust sucks, because he have to deal with it everyday in its big avionics codebase and any mistake can cost million of dollars or peoples lives. I do believe (not as a religion, but based on the progress made with languages like Rust, Idris, Haskell, Typescript etc) that the trend towards provable/robust safeness will continue in the coming 10 years. Progress is slow, but it is there and the libraries + proof assistants (possibly AI assisted) will improve. Somehow that will find it's way in one or more of the languages we are using now (because shiny new things). Anyway; I don't have that feeling, at all, about languages and codebases I have been using for 1 or more decades; c, c#, php, java, pascal, perl (only exception is JS; it was awful 10+ years ago and I do like to complain about that but I maintain only 1 significant codebase in 'older' js (about 8 years ago?); it is a (callback hell) nightmare, currently being rewritten in c#); I work on significant sized codebases in all of these and they work fine (no money lost, no people died (no avionics either though, but still enough opportunities where people could've died because of something I wrote or was lead on)). > Its psychology. We need the shiny new thing to give more meaning to our lives. 'We need' => maybe most people do, I don't. I actually never really liked new things. I want stability as my work demands and has demanded that for decades and it creeped into my non-work life. I want things to be reliable and robust 'forever', not new things that I don't know of how good or solid they are (spoiler; they are usually not, in code nor meatspace). I like to pay people, keep my company healthy and sleep at night; shiny new things do the opposite in most cases.
- ackbar03 6y agoI've never actually had a problem with c++ grammar or syntax or logic What I do have a problem with is trying to interface with more complex apis and functions. For example a while back I had to implement a https get and post request and it was a total nightmare. Something that takes only a few lines in python took a few days to figure out. Maybe it's lack fo experience but I tried wrestling with libraries like pocco which I couldn't figure out for the life of me but in the end ended up writing a monster of a program implementing the winhttp api directly. I made a similar comment earlier and someone suggested I should have just used libcurl. How to people normally wrestle with these things without going crazy?
- fxtentacle 6y agoBy using libcurl. I run a distributed c++ database and it's one of the most stable components of our stack. Java and Ruby tend to break much more often. Also, you wouldn't want to use Python without any packages, so why insist on the same with c++?
- ackbar03 6y agoIs there some sort of standard / commonly accepted way to manage packages for c++? In python its as simple as pip install + import, and the community is generally in agreement with the best library to use with good documentation. Is there some sort of similar tools I can use for c++?
- reanimus 6y agoYour system package manager, usually, along with something to detect/configure dependencies (autotools, CMake, etc). CMake can be set up to automatically download missing dependencies in some cases, too, and I think there are some other build systems that provide this sort of functionality. But there's not some standard packaging system a la pip or cargo or the like.
- barumi 6y ago> Is there some sort of standard / commonly accepted way to manage packages for c++? As others have pointed out, CMake is the de facto standard in C++. However, a combination of CMake with Conan seems to take care of most of anyone's needs. The downside is that the availability of C++ packages in Conan tends to be very limited.
- viraptor 6y ago> This code compiles, runs and works [1] on all major platforms using only the default toolchain provided by the OS vendor without any external dependencies or downloads. This is something that no other programming language can provide as of date. Isn't that provided by at least Golang and Zig currently?
- msla 6y ago> This code compiles, runs and works [1] on all major platforms using only the default toolchain provided by the OS vendor without any external dependencies or downloads. I don't know, my OS vendor provides Bash, Python, Perl, and a great whack of CLI programs and libraries. I know Python programs are pretty useless on systems without Python interpreters, but so's an ARM64 binary on an x86-64 system. I get what the quote is trying to claim, but it doesn't stand up to much scrutiny.
- lultimouomo 6y agoI don't think that all major OS vendors provide toolchains for Go and Zig. I also don't think it's a very relevant point to be honest.
- black3r 6y agofor me the problem with C++ is not about the verbosity itself... it's more about how generally incomprehensible maybe even hostile it is towards you if you lack experience compared to other languages I've worked with (JS, Python, Java, Go, ..): - navigating through template compilation error messages is a pain. - standard library is getting better, but still feels lacking. - different commonly used libraries have different code styles and reimplement the same things in different ways. - combine the previous two and you get small-ish projects where you have 4 or more different types of strings (char, const char, std::string, QString, ...) - no standard build/publish/compile/library distribution system makes using less-known external libraries a giant pain in the ass.
- mraza007 6y agoIsn’t c++ heavily used in financial industry and hedge funds
- 29athrowaway 6y agoYes... check out this repo: https://github.com/bloomberg/bde https://github.com/bloomberg/bde, a very powerful library developed by Bloomberg. A random example: https://bloomberg.github.io/bde-resources/doxygen/bde_api_prod/group__bdlcc__singleproducerqueue.html https://bloomberg.github.io/bde-resources/doxygen/bde_api_pr...
- mraza007 6y agoThanks for sharing, Bloomberg has been a huge user of C++
- balaam 6y agoC++ fills a niche and probably if you use it all on your own you don't even see the problems. But if you use it at scale with multiple developers you can see it's layers of leaky abstraction laid down since the 80s that can never really be cleaned because too much is built on this foundation. This slightly over 100 page book on move semantics https://leanpub.com/cppmove https://leanpub.com/cppmove shows some of the iceberg like complexities dotted all over the place. Some developers probably never use and have never even heard of move semantics. I've been programming in C++ pretty much my entire career. Personal projects or small projects I'd use Ruby or Python first. I'd only ever use C++ (or a very specific subset of it) if I want to make something extremely performant. C++ will eventually peak and die off but the timeframe is probably measured in decades and I'm sure there'll places where it holds on even then, like Fortran today. I certainly would't recommend it to a programmer starting out today, instead C or Rust would be better places to get an idea of system level programming.
- jnxx 6y ago> This slightly over 100 page book on move semantics https://leanpub.com/cppmove https://leanpub.com/cppmove shows some of the iceberg like complexities dotted all over the place. Some developers probably never use and have never even heard of move semantics. I think Scott Meyers' "Effective Modern C++" which is in large part a collection of caveats and description of things which don't fit always together also underlines that impression: https://www.amazon.com/Effective-Modern-Specific-Ways-Improve/dp/1491903996/ref=sr_1_1?crid=28XJMTQ15YC8B&dchild=1&keywords=scott+meyer+effective+modern+c&qid=1602934640&sprefix=Scott+Meyer+Effectuv%2Caps%2C244&sr=8-1 https://www.amazon.com/Effective-Modern-Specific-Ways-Improv...
- mbeex 6y agoMy entry in professional C++ programming was accompanied by Scotts earlier books. The moment gradually to refrain from the language as my main tool again coincides (coincidence?) with his retreat.
- j1elo 6y agoHard agree. I was enthusiastic about reading that book when I got it, as I'd been very late to the bandwagon of new C++11 and C++14 features. Ended the book in a pessimistic tone. It looked more like a cookbook of pitfalls _everywhere_. Every new feature looked exciting, but came with a list of cases where the language decides to leave you on your own when it gets too uncomfortable (the "well that's undefined behaviour, I'm sorry, you suck! bye!" escape hatch). So in the end it's like you said: a new list of gotchas to learn by heart.
- pwdisswordfish4 6y agoBetween ‘most vexing parse’, ‘static initialization order fiasco’ and ‘abominable function types’, C++ probably has more terms for miserable failures of design than any other language. That has to count for something.
- boltefnovor 6y agoThe problem with C++ is that it depends on you being an awesome C++ programmmer to avoid getting it horribly wrong.
- didibus 6y agoSerious question to those in the gaming industry: I heard C++ is mostly dominant there, can any other language even be considered for writing a game engine in? For serious AAA titles?
- jpcooper 6y agoGame Oriented Assembly Lisp: https://en.m.wikipedia.org/wiki/Game_Oriented_Assembly_Lisp https://en.m.wikipedia.org/wiki/Game_Oriented_Assembly_Lisp
- steveklabnik 6y agoThere are two studios that are working on significant big projects in Rust, Ready At Dawn and Embark. We'll see! (There are of course a number of non-AAA games too, but since you asked about that specifically...)
- Pombal 6y agoMost studios wouldn't consider changing from C or C++, but the only other realistic options as of 2020 are D and Rust.
- Netcob 6y agoI never even really got to the point where most of the stuff from the article would be relevant to me. Whenever I'm forced to using C++ only a tiny amount of the time is spent actually implementing my ideas. Most of the time is spent figuring out how to fix incredibly cryptic compiler error messages that usually have nothing to do with what I actually did wrong. Then I have to figure out how to get all the dependencies in a way that will still work in a year or two, without directly committing them to my git repo, and setting up various complex build tools that were created decades before anyone even imagined package management. Finally I hope that nobody will ever look at my code because I definitely didn't follow "best practices". The best thing I can do is sprinkle "const" wherever I can because of my religious belief that immutability should be the default. If I wanted to stay up to date with the latest developments in C++ and the accompanying proper ways of doing things I feel like I'd have to forget what little I know about the language every time I used it and learn it all over again, just to avoid doing stuff that some blog post now says is "considered harmful". I might as well try staying up to date with JavaCoffeeTypeScript using the latest AngularReactVue and whatnot.
- zeroc8 6y agoI've been programming C++ for years. Trying to keep up with modern C++ took a lot of time, which I feel is better spent on other stuff, like reading "Designing Data Intensive Applications" or something similar than yet another Scott Meyers book.
- psyclobe 6y agoIf you dedicate a large amount of your career on C++, you can be quite productive writing very robust performant code, and these days its getting easier and easier. I've been coding C++ since 1996, and to this day it is still a joy. I do a lot of back end node/typescript, and after dealing with the loosy goosy types and stuff in that language, coming back to a concrete hard core language that requires a much higher intellect to write in, is frankly refreshing. I've always felt writing in C++ requires much more skill, and that alone is a very rewarding experience. I can tune things like arena allocators and make string operations insanely fast, things I agree most problems simply don't require, but still, its a craft that I feel very proud of conquering, and every day you learn something new. So if you like a challenge, if you like learning, or maybe if you simply enjoy flexing your brain cells a bit more then most, C++ delivers that on all fronts. As for whether it deserves a bad rap, that's a little too generalized of a statement, and it reeks of dogma. Ignore dogma, dive in, learn for yourself what you think sucks or doesn't.
- gypsyharlot 6y ago"I've always felt writing in C++ requires much more skill, and that alone is a very rewarding experience. I can tune things like arena allocators and make string operations insanely fast, things I agree most problems simply don't require, but still, its a craft that I feel very proud of conquering, and every day you learn something new." I worked with C++ for years, and I while I agree with the "every day you learn something new part", I also think that most employers and projects don't benefit all that much from time spent playing with your toy of choice, so to speak. That time that you spend learning about C++ each day, could go into learning about security, machine learning, graphics pipelines and a lot of other things. I switched to a job where I mostly had to use C or Python, and I no longer obsess over my hammer. Unlike my C++-job, we don't go to C++ conferences and spend meeting after meeting talking about the language we're using. We attend conferences on crypto, machine learning, intrusion detection, and other things that could be useful to us. I agree that there is a time and place for C++, but I feel so much more productive pulling that tool out of my toolbox AFTER I've identified a hot region of my code, and then using it where absolutely necessary.
- pizza234 6y ago
- pdimitar 6y agoI have nothing against C++ per se. Used it on and off for 10 years (but most actively 3). It's a fine language. To me using C++ means you are ready to give up a lot of time and energy in order to gain a complete control over certain aspects of your program. I was very much into that at the start of my career and gradually started drifting away to more immediate productivity while reserving the right to poke under the hood when necessary. This has led me to Rust and I find it to be the better natively compiled strongly & statically typed language, but YMMV of course. These days I reach for dynamic languages for personal projects and experiments. I want to sketch an idea and see if it works in the interval of 15 minutes to a day. Languages like C, C++, Rust, D, Nim, Zig, Fortran, Pascal, Haskell, I found to be generally terrible for when I am in a flow state. Using Elixir / JS / OCaml I found that I could iterate much faster. I never will participate in a language war (although all of us have slipped on that ice more times than we'd like to admit, let's be honest). But to me C++ is simply not productive. It feels like having to learn a 10x5 meters of control panel with dials, blinky lights, keys and levers. I know there are many who enjoy that -- more power to them. But I am not in that group.
- auggierose 6y agoI find it very interesting that you put Haskell in one camp, and OCaml into the other. I am more of a Standard ML guy instead of OCaml, but can you elaborate a bit why you feel you can iterate faster in OCaml than in Haskell?
- eru 6y agoOCaml is quite a lot more pragmatic and 'loose' than Haskell. But that's just my impression. They even have for-loops in OCaml.. (I would be really slow writing code in vanilla JavaScript. There's no static checking, and not much dynamic checking. So you need to watch your step very carefully---in some sense, very much like in C++.)
- pdimitar 6y ago> OCaml is quite a lot more pragmatic and 'loose' than Haskell. But that's just my impression. Mine too. I still dislike the lack of Unicode strings by default, and the somewhat confusing tooling (initially) but outside of that I quite love the language. It has a huge potential and I can only hope that the arrival of Multicore to the upstream language will kick it forward and put it in the same league as Rust (although due to GC it can never be that fast I'd think; but who knows).
- cute_boi 6y ago1. Legacy that u can never learn 2. Too many gotchas. I am sorry but there is no reason to choose c++ for new projects especially when there is Rust, Go etc. But legacy app is exception .
- Galanwe 6y agoStopped reading after the first paragraph when author trivially states that finding filenames ending in .txt (and getting words within them) "calls for regular expressions".
- yyyuutt 6y agoI still love C++ but rarely code in it any more. One interesting thing is that the whole modern approach to immutable data structures seems so wasteful to me now. C++ you literally take strings and overwrite characters, where now people duplicate lists of records just to stay clean. Once you have the discipline you need in C++ to make mutable data structures work its a hugely efficient place to be. However I sleep much better in the non-C++ world.
- Measter 6y ago> C++ you literally take strings and overwrite characters, where now people duplicate lists of records just to stay clean. When you're dealing with UTF-8, you can't overwrite your buffer in the general case because changing case can change the encoded length of the characters.
- dynamite-ready 6y agoI'm not an expert at all, but I think C++ as a language is fine. It's the build and linking step that really frustrates me. Especially in this post Ruby, module and package age. CMake helps, but the fact that it's been around for 20+ years, and is still the best tool of it's kind, is food for thought.
- roca 6y agoThe code for that blog post is fragile in an interesting way. Its safety and security depend on a subtle invariant: that the 'word_regex' does not match a string containing any non-ASCII character. If requirements changed so the regex could match a non-ASCII character, then one of the 'c' chars could have a negative value other than -1. https://en.cppreference.com/w/cpp/string/byte/tolower https://en.cppreference.com/w/cpp/string/byte/tolower says "If the value of ch is not representable as unsigned char and does not equal EOF, the behavior is undefined", so executing std::tolower(c) would trigger undefined behavior, i.e. a safety and security bug. This fragility is not at all obvious in the code. It is easy to imagine someone making that kind of change to word_regex and introducing a theoretical security bug that no compiler or static checker is going to pick up (AFAIK). Of course the severity of the bug in practice depends on what std::tolower does in that undefined-behavior situation (which may depend on the run-time locale setting). I think the author's example actually illustrates the C++ safety problem pretty well. You write a program that looks safe and actually is safe, but slightly different code which looks just as safe is not. You're tiptoeing through a minefield.
- jleahy 6y agoIn at least some locales tolower segfaults under that condition, in glibc at least. (before anyone says that ‘in reality it’s probably fine’)
- parenthesis 6y agoI would love to know an example of that.
- gpanders 6y agohttps://drewdevault.com/2020/09/25/A-story-of-two-libcs.html https://drewdevault.com/2020/09/25/A-story-of-two-libcs.html
- roca 6y agoThat quotes a glibc comment "we also support negative `signed char' values for broken old programs" which means the OP code is in fact going to behave OK with glibc, providing that "support for broken old programs" is never removed.
- fulafel 6y agoThe example program's safety review missed UB triggered by the count potentially overflowing (depending on input). My answer: yes it does.
- PeterisP 6y agoMy beef with C++ is with its dependency (non)management. For almost every modern language, you can easily build and run code - pull code from repo, run the included script or standard command to get the dependencies and build it, bam, you're done without needing to know much about that language. With C++ it seems like half of the time pulling someone else's old project from github and running make (or whatever the author's instructions in README are) results in failure with some error that's tricky to diagnose and fix. For example, you would get some weird code error message that has zero indication with the actual cause which is that your system has a newer version of some core library than the author had.
- jstimpfle 6y agoMight just as well be a strength. At least you won't get these packages that will pull 309 dependencies, and that might build or not with the dependencies that are automatically pulled or not (with a considerable chance that it doesn't). With C/C++, there's a bigger manual upfront investment if you want to integrate a library, but it might just be that you get cleaner libaries.
- umanwizard 6y agoThe dependency manager for C and C++ is called apt-get.
- blandflakes 6y agoI didn't know C++ was bound to debian-derived operating-systems!
- lenkite 6y agovcpkg/conan solves this headache quite well now.
- wffurr 6y agoModern C++ can be a joy to write, and is fine for a lot of tasks. It's hard to beat the combination of performance characteristics and higher-level constructs. The issue with C++ is that it's unsafe by default. Foot-guns abound. The right way is to make everything safe by default and provide an escape hatch when needed, e.g. Rust's unsafe or C#'s unmanaged. Unfortunately, there's no way to "fix" C++ to be safe-by-default. Too much legacy code out in the world and no appetite in the standards committee for backwards-incompatible changes in future versions of the standard. It seems obvious to me that e.g. C++2X should entirely drop some older, broken, unsafe concepts, e.g. auto_ptr is the first thing that comes to mind, but there's all kinds of gnarly bits that need to go, and just allow older code to continue compiling under previous versions of the standard. That does leave libraries in a tough place - if your project wants to move to the (never going to exist) backwards-incompatible C++2X, they would need to update or remove all libraries not compatible with the new version. But this seems like a way to eventually move the entire ecosystem to a better place. Possibly the only way.
- tails4e 6y agoI wonder would a compile time switch that enbales 'safe by default' be an option. At least then it means programs could transition to becoming fully able to compile in this safe mode and only let subsets (e.g. certain files in a project or old libraries) use the unsafe by default mode. It would be less of a sharp shock and could allow people time to transition, and know where to spend efforts to become safer.
- dblohm7 6y agoOne thing we do in the Firefox codebase is build using a clang plugin that we wrote to statically enforce additional rules. It’s not a perfect solution , and obviously not built in, but it is a big help for avoiding footguns.
- wffurr 6y agoYou can do a lot to make modern C++ programming safer with linters, clang-tidy, sanitizers, valgrind, etc. But it's a lot of work and a lot of compute to bolt that on top of a fundamentally unsafe language. It's out of reach for a lot of organizations and requires a substantial amount of organizational coding discipline. It's like the old saw that gets trotted out about C and C++; you can write safe code in any language if you're disciplined about it. The point of safe languages is to make it easy and accessible to write safe code; to design into the language a "pit of success" rather than requiring a big slog to make a flawed language usable.
- ironman1478 6y agoC++ has a serious tooling and discoverability issue. The syntax of c++ can be annoying and there are other oddities, but that isn't going away. C++ isn't about making the easy things easy, it's about making the hard things not intractable (you can't build a self driving car or a game in python). It's unfortunate that the compilers don't automically turn on -werror, -wall and other useful flags that can help alleviate lots of arcane issues. I also think the tool maintainers do a poor job of promoting the use of UBSAN, ASAN, TSAN, etc. If you watch talks, you'll learn about these tools that solve most headaches, but you have to be so in the know to be aware that these tools exist. You have to dedicate time outside of working hours to really absorb all this information and imo that's unacceptable. Other languages put a larger effort towards making their tooling easy to use and provide amazing documentation (c# is the best at this imo). I'm a c++ dev and I love it in a masochistic way, but if these issues aren't addressed rust will eat c++'s lunch.
- mannykannot 6y agoI have to say that, as I read the author's detailed description of the program, I wondered if this was sarcasm! I don't think it is, and I don't think it would be particularly persuasive if it were, but given Poe's law, you can never be sure... As for the claim "As this program has only one thread, it can be formally proven to be thread safe": well, it is technically correct, but it just looks like a somewhat desperate attempt to make something out of nothing, when compared to, say, "thread safety is not an issue here."
- ph2082 6y agoI been programming Java for around 10 years. I tried multiple times to switch to C++. But tooling is turn off. May be I am spoiled by Java. What I want is easy build and dependency management system like maven. I wish few professional C++ dev unite and build an open source tool like maven (assuming it will not take lot of time) which allow me to: 1. Create a project from skeleton project 2. compile 3. test 4. build/run 5. Key=value=version type system to download and auto build dependency. That's it. :) I tried building myself, but I think it is too much for a beginner project. I named the project 'goat'.
- ngrnjp 6y agoStop reading after Regex.
- fabel-x 6y agosfdgfgjhj
- mpurham 6y agoThe thing with programming in general is that everyone will write code differently depending on how they look at the problem. The best programming language is the one you are most familiar with. Yes you can write faster code in Ruby,Rust,Python etc but often times those languages hide soo much code, leaving you with a sparse understanding of the underlying concepts. Language wars are not my forte but, I say use the language you are most comfortable with and become very good at using it. What takes you 30min in c++ may take me 5 min and vice versa. Happy coding!
- ebj73 6y agoI'm a bit late to the discussion, but worth mentioning here is that C++ has grown as a language on GitHub for the past 8 years: https://madnight.github.io/githut/#/pull_requests/2020/3 https://madnight.github.io/githut/#/pull_requests/2020/3 I think it's mainly due to the introduction of C++11, C++14 and C++17, which _has_ rejuvenated the language, despite the criticism. Discussions like this one tend to be sort of skewed, because opponents of an old technology, like C++, tend to be more vocal in their opinions. Likewise, proponents of a new technology, like Rust, also tend to be more vocal. It becomes sort of noisy. Behind the noise, though, I think the fact remains that C++ is still very solid, and probably even more so than it was just a few years ago.