8 ms·
C++11/14 Idioms I Use Every Day
- cheepin 12y agoThanks for this. I've been wanting to pick up a bit more new C++, but haven't found a lot of great resources.
- shiloa 12y agoAgreed. Following https://gobyexample.com https://gobyexample.com and http://rustbyexample.com http://rustbyexample.com, a http://cppbyexample.com http://cppbyexample.com kind of site would be quite useful for people who are familiar with coding and just want to experience some practical use cases in idiomatic C++ (threading, json parsing, etc).
- shmerl 12y agoC++11 has some tricky changes which are way not obvious at the first glance. A few useful resources I found: * http://thbecker.net/articles/rvalue_references/section_01.html http://thbecker.net/articles/rvalue_references/section_01.ht... * https://en.wikipedia.org/wiki/Copy_elision https://en.wikipedia.org/wiki/Copy_elision * http://en.cppreference.com/w/cpp/language/eval_order http://en.cppreference.com/w/cpp/language/eval_order * https://akrzemi1.wordpress.com https://akrzemi1.wordpress.com * https://dl.dropboxusercontent.com/u/13100941/C%2B%2B11.pdf https://dl.dropboxusercontent.com/u/13100941/C%2B%2B11.pdf Understanding the combination of copy elision and move semantics (when and how they are applied) can require one to read the standard. C++11 is not simpler than older C++, but using it is easier, if you have a good understanding of it.
- tdicola 12y agoLooks like a great list of handy things from the latest versions of C++. I think it might have been a non-standard addition before C++11, but I really like the data() function on vector. It just gives you a pointer to the first element of the array of data in the vector. Obviously you can shoot yourself in the foot pretty badly with this, but it's great for interfacing with legacy C code, etc. that expects to get a pointer of things and length.
- GFK_of_xmaspast 12y agoI think you could also have done something like "&(v[0])" to get the same thing.
- DerekL 12y agoWatch out! "&(v[0])" has undefined behavior if v is empty. "v.data()" always works, besides being more readable.
- robotresearcher 12y agoI looked this up: "Returns pointer to the underlying array serving as element storage. The pointer is such that range [data(); data() + size()) is always a valid range, even if the container is empty." Can someone explain the semantics? If the range is valid for an empty vector, what does that say about the validity of tge pointer returned? What value will it have for an empty vector?
- SamReidHughes 12y agoThe pointer will have a non-trap representation, if that is even a thing in C++. I wouldn't even assume it's non-null or not a value shared between different vectors. You can also add or subtract 0 to the pointer, or subtract the pointer from itself.
- DerekL 12y agoOn an empty vector, data() can either return a null pointer, or a pointer to some allocated memory with suitable alignment for that type, but there doesn't have to be a existing object. What is the range [ data(), data() + size() ) anyway? It consists of n + 1 iterators. All but the last one can be dereferenced. You can take one iterator in the range and add or subtract to get another one, as long as you stay in the range. You can subtract iterators to get a signed integer. You can compare iterators with all six operators ==, !=, <, >, <= and >=. For any valid pointer p, null or not, [p, p) is a valid range of length 0. It has one iterator, p, but you can't dereference it. You can add or subtract 0. You can subtract p from itself, getting 0. And you can compare it with itself.
- santaclaus 12y agoI'm loving the new pseudo-random number support. In a few lines one can crank out some Mersenne twister niceness. No more shipping around custom pseudo-random code, and no more calls to rand that give different results for the same seed on different platforms!
- forrestthewoods 12y agoRaarrggghrhghh. I couldn't possibly disagree with his proposed use of 'auto' more. Abundant use of auto is the opposite of readable! Nothing is more infurating than jumping into a new bit of the code base and having no idea what anything is or what it can do. Auto is acceptable for iterators and, in some cases, references to complicated containers. Don't fucking type "auto pos" instead of "Vec2i pos", "Vec3f pos", or one of many other possible types that pos variable may represent.
- nawitus 12y agoWhy don't you use an IDE that shows you the type? I do agree that jumping into a new code base can be slightly more trickier if type inference is used, but it's a minor point compared to the benefits in my opinion. If you cherry pick something like Vec2i, type inference doesn't look that good, but the benefits are clearer from more complex code.
- serge2k 12y agobecause the code base has several million lines and eclipse is a horrific user experience? The example posted is a horrible use of autocomplete. >const int calculated = [&] { auto l = lock(); auto first = stage1(); auto second = stage2(); return combine(first, second); }() No idea what that does. It takes 2 variables of some type and does something too them. There is some sort of lock there too. I guess.
- nawitus 12y agoSo is the core problem that there's no decent IDE for C++ which can identify the "autocompleted" types to the developer?
- SamReidHughes 12y agoNo, the core problem is a developer that thought "auto" exists to make code easier to write instead of existing to make code easier to read.
- santaclaus 12y agoHas anyone taken a look at the new versions of Bjarne Stroustrup's C++ Programming Language [1] or Scott Meyer's Effective Modern C++ [2]? The originals are classics, and I would be interested to know if the new versions hold up. [1] http://www.stroustrup.com/4th.html http://www.stroustrup.com/4th.html [2] http://shop.oreilly.com/product/0636920033707.do http://shop.oreilly.com/product/0636920033707.do
- danielweber 12y agoI got [1]. (My first copy had several sections misaligned, which I thought would make a hilarious "offset" bug, but no one else did, so I sent it back for a replacement.) It's interesting and readable. I used to keep a listing of all the typos and errors I found but that project got buried beneath other things in my stack.
- tdicola 12y agoI read his short A Tour of C++ and enjoyed it a lot. Much of it is taken from parts of his update to The C++ Programming Language. If you just want a short book to introduce the new parts of C++11, A Tour of C++ is the way to go.
- agwa 12y agoI have the 4th edition of C++PL, and while I haven't read it cover to cover (it is long) the parts I've read have been excellent and definitely meet or exceed the standards of the earlier editions.
- dfan 12y agoThe 4th edition of Stroustrup is quite good, and much better than the 3rd edition, which was not even very usable as a reference, due to a terrible index. It's still not a page-turner, though.
- thebear 12y agoThanks for this blog post; it will help me to make the best use of C++11/14 features in day-to-day programming. One thing I've been wondering about for a while is how the auto keyword relates to type-safety. The blog post lists the point "auto type deduction everywhere" under "type-safety". But consider the line auto x = foo(); Suppose you refactor your code, and in the process, the return type of foo() changes. Without the use of auto, the compiler would produce an error message, alerting you that the above line of code may need your attention. As it is, with the use of auto, the above line will compile no matter what. In other words, that particular line now behaves as if C++ was an untyped language. Isn't that a step down as far as type-safety is concerned? Please note: I'm not asking here whether that's good or bad. I'm asking, "Assuming that we use the auto keyword throughout, can we still call C++ 'strongly typed'"?
- nawitus 12y agoI think the compiler would give an error if the variable x is (later in the code) used in a way that's forbidden by the type.
- thebear 12y agoYes, that's correct. It is, in fact, the same kind of behavior you get with templated code: you can instantiate your template with any type you wish; compile errors will occur when the instantiation is used in ways that are forbidden by the type. This behavior has been recognized as less than ideal, and the issue will be addressed by concepts. My question is: if we have this behavior not only for templates, but for every variable, isn't that less type-safety? Isn't that less than 'strongly typed'? (Come to think of it, I think I'm really asking about the definition of 'strongly typed'.)
- scott_s 12y agoIndeed you are. There was a post from two weeks ago on the topic, called "What is type safety?" HN discussion here: https://news.ycombinator.com/item?id=8137332 https://news.ycombinator.com/item?id=8137332
- 12y ago
- dfan 12y agoThe nice thing about C++11 is that the designers seem to have actually tried to increase usability, rather than just maximizing expressivity, which is usually the case. Features like range-based for and auto make programming much more pleasant. I program in a functional style in many other languages, but could never bear to in C++ before because it was so awkward.
- Silhouette 12y agoI still wouldn't try to use too many functional idioms in C++ even now. It's just not a good language for that kind of programming style. For example, from the "New language features" section of the C++14 Wikipedia page[1], the first example is generic lambdas, which means we can now write: auto lambda = [](auto x, auto y) {return x + y;}; That's progress of a sort, but in Haskell, a language designed to support this style of programming, it looks like this: lambda = (+) Obviously C++ is slowly being left behind by modern programming language design and the collective experience of the programming industry over several decades since C++ was invented. Eventually it will be superseded by other languages that do support more expressive language features and better designed standard libraries (which is easy to do with the wisdom of hindsight, of course -- this is not a criticism of the people who built C++ without the benefit of that hindsight). But since we don't yet have any such alternatives that don't also have significant drawbacks and/or unacceptable run-time performance characteristics, for the near future C++ is still going to be the first choice for a lot of projects in the real world. In that respect, closing the loopholes and fixing the pain points is useful for a lot of people, and very wisely that seems to be what the standards committee are concentrating on doing. [1] http://en.wikipedia.org/wiki/C%2B%2B14#New_language_features http://en.wikipedia.org/wiki/C%2B%2B14#New_language_features
- dfan 12y agoI agree with your example. But, for example, before C++11, if I wanted to do an even slightly non-trivial map or filter I'd probably do it by hand rather than write a (C++) "functor" or assemble some function in place with std::bind1st et al., whereas now I will happily write a simple lambda.
- deleted 12y ago[deleted]