9 ms·
Smart pointers and move semantics in modern C++
- hellofunk 10y agoThere are other C++11/14 features that improve performance even further that are not mentioned here. For example, automatic type deduction often finds a more correct type for a variable or iterator than you'd guess on your own, since your guess might require an implicit conversion which might be costly in some cases. Brace initialization can also avoid costly implicit conversions. And using lambdas rather than named functions often leads to automatic inlining, an additional performance benefit. C++ is a changing language and is doing a good job keeping up the with times, adding high-level features while increasing performance at the same time.
- KKKKkkkk1 10y agoThe calculus here is simple. You have two options: 1) Spend 90% of the time writing performance-neutral code in a modern high-productivity language and 10% on performance-critical code in a modern high-performance language. 2) Write everything in a "performance beast" of a language, spending 90% of your time fighting said language and 10% delivering useful functionality. Bottom line, if you choose option 2, you spend 10x time delivering the same functionality and performance and you force yourself to hire the kind of expensive developers who are willing to waste their time mastering modern C++.
- thesmallestcat 10y agoWhy would mastering modern C++ be a waste of time?
- angersock 10y agoBecause, for better or for worse, every second spent mastering a language is time not spent delivering value. EDIT: How many dollars have you been paid for template metaprogramming? How many contracts have you won because you used the proper const-correctness? Folks, nobody gives two shits about how pretty your CPP (or any code for that matter!) is if it isn't solving their problem right now. More value has been created by decent developers using the boring language features they know well than by people becoming master craftsman.
- mikeash 10y agoIf it helps you deliver value faster afterwards then it's a win. Alice starts cutting down a tree with a dull saw, Bob takes the time to sharpen the saw before he starts cutting. It's not sensible to criticize Bob on the basis that his sharpening time is time not spent delivering value.
- angersock 10y agoThere is rarely an afterwards in any meaningful sense: https://en.wikipedia.org/wiki/Superiority_%28short_story%29 https://en.wikipedia.org/wiki/Superiority_%28short_story%29 If you want to see your position taken to the extreme, go look at the JS ecosystem right now. Plenty Bob's sharpening their axes to the detriment of both their projects and the community as a whole. As engineers and programmers we like to play with tools and pursue language purity and whatnot--but we cannot fall into the trap of conflating that with sound business practice.
- mikeash 10y agoPretty much any idea becomes stupid when taken to an extreme. If you want to see your position taken to the extreme, go look at 90% of programmers out there, who spend as little time as possible sharpening their saw and as much time as possible churning out awful, nearly worthless code.
- angersock 10y agoQuantity has a quality all its own, my friend. Wordpress is garbage, but has a fairly secure niche that is only recently even getting attention from competitors. Here on HN everyone is a PLT prodigy who would never deign to admit that they would ever be beaten by the 90% of programmers--but in the real world, well, they make shit happen. Some problems are solved better by throwing warm bodies with lukewarm IQs than by trying to get the perfect language lawyer. Have some humility.
- 10y ago
- hellofunk 10y agoYou forgot option 3), which I use myself: Write in a high-performance language that also has high-level features, and write 90% of your code without concern for the language's cool optimization features. That's what I do and it's great. I don't use move semantics or think about them, I avoid heavy templates, and I focus a lot of my work on the functional tools in C++ now and the more elegant ways of doing stuff at a high level. For when I need those extra optimizations, no need to change languages, I'm already there.
- ced 10y agoHaven't used C++ in a decade - how is the modern functional programming working out without a GC? Isn't object ownership tricky to untangle? I read your option 3 and nodded - I'm using Julia for much the same reasons. I didn't expect C++ to be the answer, but it's cool that it can work out.
- cjhanks 10y agoIf you are using Julia, then I will presume you are primarily working in some form of numerical computing. It is a very wide field, so it is difficult to say if object ownership will be tricky or not. If you are working with (b|m)illions of particles or entities which are capable of changing ownership, you will have a hard time in any language. Whether that's the C++ ownership being unclear or the garbage collector defragmenting your memory (just because you don't see the issue doesn't means it's gone in GC languages). That said, typically I find most algorithms have a computable upper-bound memory constraint and so you just pre-allocate a slab and then objects reference it. You will usually get better cache coherency and less wasted operations/sec. You're left with only a couple pointers you need to delete when you're done with the structure. As for `functional programming`, it depends on what you're looking for. C++ has two killer features for this, in my opinion; expression templates can seriously improve performance of functional composition (see Eigen3), and compile-time elision of type-dependent code branches (like a static if). Since I have learned to use `unique_ptr`, `shared_ptr`, `weak_ptr`, (`deferred_ptr`), and to prefer idiomatic accessors like `.at`, `.find`, `.insert` I cannot recall the last time Valgrind was angry at me. I think I end up writing `new` and `delete` maybe once a month(?). If I was designing widgets or applications with hard to define user interaction, I imagine I would have more complaints to share.
- ahamino 10y agoApplications that employ computer vision, machine learning or even deep learning, especially if they are trying to run models on mobile devices have to write their codebases on an efficient high-performance language otherwise, their apps will be just too computationally expensive (too slow). At my company, three quarters of our codebase is written in C++ because performance is very critical for us, in addition portability! i.e we can compile to run the same code on different platforms without added layers of translation.
- EpicEng 10y agoPerhaps this is true for your applications (and why no option 3: developer knows C++ well and is efficient in it?), but not all of us can goof around with GC's and a complete lack of performance oriented features. Not all of us have a huge runtime to support our language which runs on our target platform. Not all of us write code which is 90% boring, UI or CRUD type stuff. Not all of us are ok with delivering bloated applications that require hardware upgrades to run at the same speed they ran at 5 years ago.
- AlexandrB 10y ago> but not all of us can goof around with GC's and a complete lack of performance oriented features. But apparently you CAN goof around with KLOCs of useless boilerplate and the added defects they imply [1]. [1] http://programmers.stackexchange.com/questions/185660/is-the-average-number-of-bugs-per-loc-the-same-for-different-programming-languag http://programmers.stackexchange.com/questions/185660/is-the...
- nurettin 10y agoI am fine with IDEs generating boilerplate. I am not fine with maintaining it unless it is easy to navigate to parts of code concerning what needs to be maintained. I live in a 20 year old MLOC land and whenever we need to add or change a subtle behavior, we go debugging for half an hour at best.
- user5994461 10y agoUse java, C#, or Go. You get the high productivity AND the performance together. (Also, the tooling is so much better).
- erichocean 10y ago> Spend 90% of the time writing performance-neutral code in a modern high-productivity language That's actually C++ now. I moved to it from TypeScript earlier this year and have been very happy. (Using Google's Bazel for builds has been really nice, too—I hadn't realized how much I missed having a non-OS-specific package manager.)
- cubaia 10y agoThe key here is to distinguish from the pedantic snobs from good developers. The pedantic snob will usually hold some extreme position about topics such as (1) obscure language minutia; (2) endless "framework building"; (3) premature optimization; or (4) mindless design "best practices". They will have high pride attached to whatever is it and they would add a flair of expertise to it, making you feel like you hired a genius. At the start, it looks like they are working on some super advanced wizardry, but you eventually find that they mostly waste time. On the other hand, the good developers care more about delivering value. The good developer will not waste time solving problems you don't have --thus slicing through your 90% problem like butter-- and at the same time will possess the sharp tools to solve the hard 10% problems your less than good developer is unable solve no matter the deadline. For option 1, you hire a good developer. For option 2, you hire a snob. If you hire your average cheap engineer, you get option 0: he/she will eventually do OK for 90% of the problems, but the last 10% (which is often critical) will be a mess.
- lbrandy 10y ago> Spend 90% of the time writing performance-neutral code in a modern high-productivity language and 10% on performance-critical code in a modern high-performance language. What about the other 80% of your time spent trying to get those things to inter-operate in a way that doesn't destroy the good parts of both?
- pif 10y ago> spending 90% of your time fighting said language I've been developing in C++ for more than ten year, and never did I feel the need to fight it. Actually, it was a nice travel companion. And I miss it since I was forced to switch to C#: C++ made all it could to help me do what I needed, and it was effective and smart; C# always tries to convince me to change my needs in order to do things like he prefers. In other word, C++ treated me like a professional partner; C# treats me like a newbie.
- armitron 10y agoIf only it was a reliability/robustness/simplicity beast instead. Instead, it's evolved to be this atrocity of unspeakable proportions that continues to wreak havoc (security bugs, technical debt, complexity) pretty much everywhere it's used. When the best C++ developers on the planet can not do better than that, you know we have a problem. It remains to be seen if the alternatives that are now slowly emerging will replace it. My personal estimation based on all the expert C++ programmers I know is that this will not happen through people abandoning C++ since it sits so high on the abstract ladder of complexity that for one to even begin to question its foundations (and all the time/years/decades one has sank into becoming an expert C++ programmer) will be a Tower-of-Babel moment. On top of that you have the (quite illusionary) tremendous feeling of empowerment one gets when using something that required such an investment to master. JWZ once wrote (on an unrelated topic): “No matter how hard you try, you can’t make a racehorse out of a pig. You can, however, make a faster pig.” This seems fitting to the way C++ is evolving.
- dalke 10y agoJohn Steinbeck, "East of Eden" (1952). "You can’t make a race horse of a pig. — No, said Samuel, but you can make a very fast pig." https://books.google.se/books?id=OPy6E5ZhXs0C&printsec=frontcover&dq=East+of+Eden&hl=en&sa=X&redir_esc=y#v=onepage&q=racehorse&f=false https://books.google.se/books?id=OPy6E5ZhXs0C&printsec=front...
- jnordwick 10y agoIf by JWZ you mean John Steinbeck. http://www.goodreads.com/quotes/68772-yes-you-will-and-i-will-warn-you-now-that http://www.goodreads.com/quotes/68772-yes-you-will-and-i-wil...
- user5994461 10y agoShould quote this one as well: (3) With sufficient thrust, pigs fly just fine. However, this is not necessarily a good idea. It is hard to be sure where they are going to land, and it could be dangerous sitting under them as they fly overhead. https://tools.ietf.org/html/rfc1925 https://tools.ietf.org/html/rfc1925
- 10y ago
- filereaper 10y agoDoes anyone have a good recommendation for a cannonical reference on Modern C++14? I have experience with C++ but its the old kind with raw pointers. My usual starting point is Herb Sutter's books, with Bjarne's bible handy when I need it. I'm not sure where to start with modern C++.
- lossolo 10y agoIf you have experience with C++ already then go with "Effective Modern C++" by Scott Meyers.
- hellofunk 10y agoThe official C++ FAQ is good: https://isocpp.org/faq https://isocpp.org/faq Scroll down to the sections on C++11/14.
- anuragbiyani 10y ago"The C++ Programming Language" has been updated in 2013, and includes C++11 changes: http://www.stroustrup.com/4th.html http://www.stroustrup.com/4th.html "A Tour of C++" (also by Bjarne) is a quick overview of the language (including C++11 changes): http://www.stroustrup.com/Tour.html http://www.stroustrup.com/Tour.html Another very useful resources is the FAQs from "Standard C++ Foundation": https://isocpp.org/faq https://isocpp.org/faq
- rl3 10y agoNot exactly canonical (it's a wiki), but otherwise excellent: http://www.cppreference.com http://www.cppreference.com Modern features are clearly delineated as such.
- optforfon 10y agoI'd second "Effective Modern C++" by Scott Meyers and point out that while the book was written for C++11 most of the new features of C++14 extend and polish off those existing features. Now const expressions are more flexible and powerful, template meta programming is more powerful and in general they fix a bunch of smaller issues with the standard library. So you'll learn those things as you get to them.
- 10y ago
- snissn 10y agoWow the author is giving a two day course soon in C++ for up to 40 people that is costing 2500 per person. Is that a big industry? Do many people on HN run programming workshops? I would be interested in chatting if you do. Email on my profile
- hellofunk 10y agoC++ training is a big industry, yes. Not sure about other languages.
- jnordwick 10y agoPart of the problem with the new move semantics for me, and C++ in general, is figuring out what the compiler is going to do and their interaction with the return value optimization. Sometimes I can't figure out if the RVO or the move constructor is going to be used. C++ has definitely blown it's complexity budget and the problem is getting worse. I don't really see a way out of it either. I sure hope Rust starts to gel or a better C++ comes along, because I don't think I can keep pace with C++ too much longer.
- user5994461 10y ago> I don't really see a way out of it either. Stop using C++ unless forced to do so. That's the only way to leave the complexity minefield.
- alexnewman 10y agoHeh, I think this isn't complex as much as making something complex simpler. Just super awkard because it's caked in afterwords. I'm happy to see some good examples of move constructors and the like.
- hendzen 10y agoIf you're using clang you can just turn on -Wpessimizing-move and the compiler will tell you when you have a std::move call that is inhibiting RVO. The rule of thumb is don't use std::move on a return value unless you are returning a move-only type (which forces you to do so).
- frankzinger 10y ago> The rule of thumb is don't use std::move on a return value unless you are returning a move-only type (which forces you to do so). RVO will be automatically applied if the returned variable is local to a function and of the same type as the function's return type. That's all that the standard allows. RVO is not applied to function arguments, regardless of whether or not they're rvalue references. So your rule of thumb breaks for cases such as these (X is a movable and copyable type): X f(X&& x) { return x; // x is copied, not moved } In order to get x moved into the return location, you would need to do move it explicitly. Source: Effective Modern C++ by Meyers.
- PhantomGremlin 10y agoI hope everyone read down to the end to see this factoid about Leor Zolman, the author: In 1979, Leor wrote the BD Software C Compiler ("BDS C"), the first 8080/Z80 native-code C compiler both developed on and targeted for personal computers. Leor's C compiler didn't support floating point, but it compiled programs like a bat out of hell on a 4 MHz 8-bit Z80 microprocessor with 64 KB of memory. Yes, it was C, running well, on a 4 MHz micro with 65,536 bytes of memory. Truly remarkable for its time. https://en.wikipedia.org/wiki/BDS_C https://en.wikipedia.org/wiki/BDS_C
- alexnewman 10y agoAs a rust programmer. I've been very happy to see c++ talking about the things that are core to how we get stuff done in rust. As a c++ programmer, do you ever wish that auto wasn't const by default? Couldn't you have auto (let) and volatile (mut) :) . I'm pretty sure this wouldn't be too hard to implement.
- Animats 10y agoMove semantics are a good idea, but C++ doesn't have the compiler machinery to catch when you move something away and then try to reference it. Move semantics really need a borrow checker, like Rust. In C++, you have to be very, very careful not to do things like accidentally move something passed to you as a non-const ref.
- jguegant 10y agoUse clang tidy: http://clang.llvm.org/extra/clang-tidy/checks/misc-use-after-move.html http://clang.llvm.org/extra/clang-tidy/checks/misc-use-after...
- deleted 10y ago[deleted]
- int_19h 10y agoIn C++, you can't "accidentally" move something that's a non-const ref, since a move from one would require explicit use of std::move. The only things which can be moved accidentally are rvalues and rvalue references. But for rvalues, that doesn't hurt anything; and for rvalue references, the only reason why you'd use one is if you intended to play tricks with move semantics, which implies that you know what you're doing. Basically if you write C++ as if move semantics didn't exist (i.e. never use rvalue references or std::move), you won't shoot yourself in the foot by those means. Of course, this also means that compiler assumptions are fairly pessimistic, so many places that could be a move aren't, because the move has to be explicit.
- deleted 10y ago[deleted]
- nurettin 10y agoI think most of these educated comments about memory safety wouldn't be here without the hindsight provided by Rust. So thanks, Rust!
- flohofwoe 10y agoI'm over-generalising, but: if you want performance, don't create a huge soup of tiny objects on the heap pointing to each other as can often be seen in 'smart-pointer-heavy' C++ projects. Creating and destroying objects on the heap is expensive, and you'll end up pointer-chasing with cache-misses all over place. Unfortunately smart-pointers are only useful with this 'every object lives isolated on the heap' approach, since alloc-init and cleanup-free are merged into the same operation. Of course there's ways around that by writing custom allocators, but this just adds more complexity when often granular objects with their own lifetime and ownership aren't needed in the first place. Smart-pointers are a convenience feature to not having to think about object-lifetime, and in the case of shared-pointers, also to not think about ownership, they're not about performance. If you want performance, don't allocate single objects on the heap, and spend some time thinking about data layout in memory.
- oldsklgdfth 10y agoThe vector is initialized with 500000 widget objects. The size and capacity of the vector are equal. The following while loop is never executed. >> while (vw.size() < vw.capacity()) >> vw.push_back(Widget()); In the situation that the vector is not initialized with elements and populated in a loop the time for a single push_back is equal. I think this is because there is no need for a resize. >> vector<Widget> vw; >> for(int i = 0; i < 500000; i++) { >> vw.push_back(Widget()); >> } Does this illustrate how fast a vector of objects can be copied/resized using move semantics?