News for hackers. Stuff that matters.
Re:“Modern” C++ Lamentations by 4bpp on Friday December 28, 2018 @02:40PM (#18778909)
I think that at this point, C++ has basically to be treated the same as the English language. Sure, you could write sentences that span three pages, employ Shakespearean vocabulary or words that hardly anyone has known since the abolition of Classics from university admissions tests, or encode another layer of meaning in the bit pattern of when you do and when you don't use Oxford commas. What makes something good English communication is not whether you used those features correctly, employed the most in vogue ones or found the "most elegant abstraction" ("there's this one word attested in a handful of 14th century sources that captures exactly what I want to say, so I'll use it without explanation"), but whether you have struck the right tradeoff of minimising the combined effort put in by you and your audience and conveying your message faithfully.

Of course, for English, this is exactly the sort of problem that is addressed by style guides (and teachers/peers reacting to you, and natural selection). I think what we need is more and better opinionated C++ style guides that don't just talk about what line to place your { on, but have the confidence to say things on the level of "std::move may add a marginal amount of efficiency, but greatly detracts from the legibility of code. Avoid using it altogether."

Re:“Modern” C++ Lamentations by Aardappel on Friday December 28, 2018 @02:51PM (#18778980)
There should probably be two C++ styleguides: one for library authors and one for library users. For the former, use of std::move can be absolutely essential to abstractions that are both efficient and correct. For the latter, it probably means you're overthinking things.
Re:“Modern” C++ Lamentations by 4bpp on Friday December 28, 2018 @03:39PM (#18779241)
This is a fair point, but I still feel like there should be some regulations on how it is used in libraries (lest we wind up in a "this chunk of code is going into a .so, so everything goes!" situation), since library code still has to be read and maintained.

Compare inline assembly: it can be absolutely essential to talk to hardware or use specialised processor features (like if you want to use fancy SIMD instructions in the inner loop of a linear algebra library), but everyone would probably agree that a library which keeps the actual assembler code contained inside one or two specific functions is somehow preferable to one where each of the 40 different ways of calling it happily start out with an __asm block that packs their respective arguments into the relevant special-purpose registers and only then call the common "do the actual processing" function.

Re:“Modern” C++ Lamentations by 4bpp on Friday December 28, 2018 @03:18PM (#18779139)
Personal opinions on the "right subset" of C++:

* Yes to classes.

* Yes to inheritance and virtual member functions, because interfaces are a very useful and easy to understand abstraction. Moreover, especially for games, idioms such as "class Monster : public DamageableObject" are really the most natural thing. However, avoid situations in which you need dynamic_cast like the plague. No to virtual inheritance.

 - I really wish class memory layout were standardised more, but at least some non-standard assumptions are fairly safe in my experience: e.g. class A : B {...} ... B * x; assert((long)static_cast<A* >(x) == (long)x);

* Before you start using "friend class", consider whether you could get around it somehow. If a class is not public-facing, set everything public and enforce encapsulation by self-discipline rather than language features.

* Yes to templates in their C++ 101 application of making a $type-specialised version of classes and functions. No to using them to perform any real compile-time computation, or anything of the type Boost pulls. No to Boost.

* "Keep the parts of your code that only do C stuff in C".

 - printf over iostream.

 - (de)allocate classes with new/delete, but POD with malloc/free

 - exception: std::string over char* , because it is really that much more convenient

* Yes to lambdas, but only pass them as function arguments if there is no good alternative, because of legibility. Avoid stuff like the for_each(..., []{ ... }) in the Ranges example.

* Yes to STL containers and algorithms, because everyone knows how they work and they are usually good enough.

* Range-based for over for(std::container::iterator i=...). Using the Ranges TS when a plain for loop would do strikes me as novelty-chasing and violates "do C stuff in C".

* Cautious yes to auto. It does somewhat detract from comprehension in some use cases. Don't just auto everything because you are too lazy to figure out the type.

* std::shared_ptr only when you actually think you can't answer the question of what the appropriate point to deallocate a piece of memory is, or at least not without significantly changing the structure of your code.

* Avoid std::tuple, std::variant and other awkward STL attempts to replicate functional language idiom without the syntactic support. It's terrible to read. Unfortunately, STL containers sometimes force you to use pair.

* No to exceptions; their interaction with other language features is awkward, and the eternal difficulties with platform support make me feel no confidence in the reliability of the feature. (I'm unfamiliar with the bowels of the implementation, but it seems like unwinding C++ stacks is fundamentally a hard problem.)

* No to novelty features such as user-defined literals.

* goto only to break out of multiple levels of nested loops.

* Coroutines strike me as something that's unambiguously cool but so far removed from the standard idiom of C++ programming that I'm inclined to say no. Maybe there's an alternative style guide you could write that says yes to coroutines and no to some of the things above. Multi-paradigm should not mean "use all the paradigms".

(I'm very happy to be persuaded otherwise on any of these points.)

Re:“Modern” C++ Lamentations by doublerebel on Friday December 28, 2018 @10:27PM (#18781613)
I have been exceptionally surprised and thankful for the coroutine implementation in C++ and its early adoption in Visual C++ compiler (MSVC). UI and I/O code (particularly for Windows) is much easier to both write and comprehend. The stack traces are clear and error handling is simple.

I have professionally worked in many async (and synchronous) languages, and the implementation of async in modern C++ is my favorite. That is weird to type out, but it's true. I'm really enjoying modern C++, but I do follow almost all the rules you list.

Re:“Modern” C++ Lamentations by thestoicattack on Friday December 28, 2018 @03:42PM (#18779259)
No std::unique_ptr?
Re:“Modern” C++ Lamentations by 4bpp on Friday December 28, 2018 @04:34PM (#18779613)
I haven't encountered any context in which it would add value (i.e. you can't just figure out yourself where it will go out of scope and delete at that point, which also makes the code clearer), and all other things equal, using it hides the semantically relevant type (the interesting part of a unique_ptr<A> is the A, not the unique_ptr!) and makes code and error messages harder to read.
Re:“Modern” C++ Lamentations by MereInterest on Friday December 28, 2018 @05:48PM (#18780117)
It feels like that goes with your no exceptions policy. If you use exceptions (which is a different argument), then the return point is not necessarily clear. A unique_ptr makes sure that the object is correctly deleted, even in the case of error conditions.

The compiler knows where the lifetime ends. Why do the computer's work for it?

Re:“Modern” C++ Lamentations by asdkfjasl on Friday December 28, 2018 @04:49PM (#18779725)
unique_ptr is super useful for documenting the point in the code that owns a given object, and for providing some compile time protection against multiple deletions. (If you never write delete and only use unique_ptr, you have to do a relatively foolish thing to get double deletions.)
Re:“Modern” C++ Lamentations by 4bpp on Friday December 28, 2018 @05:09PM (#18779861)
I've written some heap-heavy code and never used unique_ptr, but I don't remember ever causing a double deletion. What's a pattern which you figure makes one prone to doing that? (On that basis, I'm a little inclined to suspect that it may be more of an issue for programmers who came from a deeply memory-managed language like Java and therefore don't build mental models to keep track until when a given allocation is needed.)

(I have of course produced my share of memory leaks - praise be to valgrind - but they were all in scenarios where unique_ptr would have been too restrictive (without a Rust-style complete reconsideration of the code's ownership structure).)

Re:“Modern” C++ Lamentations by oscargrouch on Friday December 28, 2018 @07:57PM (#18780882)
One thing i like about using std::unique_ptr now that we have and use std::move() is to annotate in the API when you want to own the heap object being passed or to say that the api consumer should own the reference.

I get that if you just use it for usual the owning class, it doesnt provide that much, but it annotates lifetime, and its pretty cool when you get used to it.

if you see this:

    class X {
     Y* y;
    };
Does X owns Y? or is owned by Z and X is just using it?

    class X {
     std::unique_ptr<Y> y;
    };
Now you know for sure X owns y.

    class X {
      std::unique_ptr<Y> CreateY();
      Y* CreateY();
    };
Look how in the first example you know that X wont retain a copy of Y, and the caller will be considered the owner of the heap..

Now in the second example you are not sure if X retain and will handle the deletion of Y, and you should use Y, while in the first example its perfectly clear the api intention.

the same here:

    void AddY(std::unique_ptr<Y> y)
    void AddY(Y* y)
in the first you are aware you are passing the ownership of Y, in the second you wont be sure if you still need to handle the deletion yourself.

Before std::move() i get it, but after you can pass things by moving them, i dont get it why anyone would not like to use this.

For me this is basically the "lifetime annotation" feature, only that it is by convention, and not enforced by the compiler. Unlike others these are the reasons why i dont feel the urge to jump the Rust bandwagon, and prefer to use things like Swift when i need a more "chill" environment to work, as i didnt feel more productive in Rust than in C++, while with Swift it happened and it also has a pretty good story perfomance wise.

I prefer to mix C++/Swift as my perfect duo, than try to make it all fit in one language, as this always lead to frustation and a lot of headaches.

Re:“Modern” C++ Lamentations by summerlight on Friday December 28, 2018 @05:37PM (#18780041)
If code is completely under your control, then it's okay. But from my experience, these kinds of errors frequently stem from large code bases without a clear ownership. Think about a case that hundreds of people are working on the same code base. You may not understand 99% of code, and probably don't even want to understand all the horrors written by other programmers.

In fact, I have seen a number of horrific instances that someone decided to write clever tricks with object lifetime which leads to production crash and no one really understand (or even bother) what's going on there. The only way to deal with such code is looking into its implementation, probably for a week or two. And found that the original author has left the company.

In these cases, static type annotation helps a lot by serving as a formal contract. To reason about object lifetime, you don't need to dig into the implementation; all you need is looking into variable's type signature. Same thing can be applied to types other than those related to object lifetime.

Re:“Modern” C++ Lamentations by asdkfjasl on Saturday December 29, 2018 @10:57AM (#18784134)
Some people are robots and never write errors. I and most C++ programmers are not in that category.
Re:“Modern” C++ Lamentations by jlarcombe on Saturday December 29, 2018 @03:17AM (#18782615)
You've never found a context in which unique_ptr is useful? I find this surprising. It basically removes a class of memory management bugs with heap allocated objects at a stroke.
Re:“Modern” C++ Lamentations by int_19h on Friday December 28, 2018 @05:31PM (#18780012)
> However, avoid situations in which you need dynamic_cast like the plague.

You need dynamic_cast for dynamic interface queries ("does this object support X?"), even in the absence of virtual inheritance.

Some would say that there's no downside to always using it when you can. If what you're doing is an upcast, it's a no-op. If it's a downcast, then at least you get an exception instead of an invalid pointer that may or may not blow up if what you're casting is not of the correct type.

> Before you start using "friend class", consider whether you could get around it somehow. If a class is not public-facing, set everything public and enforce encapsulation by self-discipline rather than language features.

Why? It's a language feature that's there to help you enforce said discipline. What's the downside?

> I really wish class memory layout were standardised more, but at least some non-standard assumptions are fairly safe in my experience: e.g. class A : B {...} ... B * x; assert((long)static_cast<A* >(x) == (long)x);

That the object is allocated at the same address as its base subobject is guaranteed by the standard, if I remember correctly. Your particular assert is not, though, because long is not guaranteed to fit a pointer (and doesn't, on Win64).

> printf over iostream.

Not only you lose type safety, but it's extremely easy to write code that kinda sorta works but actually doesn't. The most common case is passing a struct with a single field to printf - this is actually implementation-defined, and some implementations detect it and treat it as invalid, while others just put the contents of the struct on stack. So it happens sometimes that people e.g. pass std::string that way, expecting it to work with %s - and it does... on that one implementation, and for that particular string. Then it breaks elsewhere.

iostream is still bad tho, both design-wise and perf-wise. The answer is actually Boost, which has proper typesafe formatting.

> (de)allocate classes with new/delete, but POD with malloc/free

There's no benefit to using malloc/free whatsoever, and it forces you to cast.

> Avoid std::tuple, std::variant and other awkward STL attempts to replicate functional language idiom without the syntactic support

Tuple has syntactic support as of C++17:

https://en.cppreference.com/w/cpp/language/structured_bindin...

> No to exceptions; their interaction with other language features is awkward, and the eternal difficulties with platform support make me feel no confidence in the reliability of the feature.

If you ditch exceptions, you might as well ditch constructors as well, since there's no way to report errors from them otherwise. You're also forced to use new(nothrow) then. Basically, the language is designed around exceptions, and excluding them is fighting it.

But I don't see the point. C++ exceptions have been supported and stable on all platforms for a long time now. On sane platforms (i.e. not x86, but e.g. amd64), they're also zero-time-cost at runtime for the non-exceptional path. It's not the 90s anymore.

Re:“Modern” C++ Lamentations by TheAccount on Friday December 28, 2018 @07:04PM (#18780524)
> But I don't see the point. C++ exceptions have been supported and stable on all platforms for a long time now.

How come we don't see exceptions being used in serious C++ projects then (e.g. Chromium and Windows)?

Re:“Modern” C++ Lamentations by int_19h on Saturday December 29, 2018 @07:03PM (#18786471)
Either legacy codebases that have rules dating back to the times when avoiding exceptions actually made sense, or else a cargo cult.
Re:“Modern” C++ Lamentations by 4bpp on Friday December 28, 2018 @07:01PM (#18780503)
> You need dynamic_cast for dynamic interface queries ("does this object support X?"), even in the absence of virtual inheritance.

I prefer using C-style casts for brevity, and implementing support queries like that explicitly (i.e. via a "type" member or GetType() function or whatever in the base class). Quite often, you wind up needing that information anyway (resulting in redundancy), and the C++ casts are extremely verbose and ugly.

> Why? It's a language feature that's there to help you enforce said discipline. What's the downside?

I've tried working with it, but in my experience this language feature very quickly consumes more cognitive energy (by having to maintain the list of friend classes and just having to deal with it being there, consuming space in the source) than it saves over maintaining discipline manually. (This maybe a consequence of me not having worked on a lot of C++ projects with a high (number of contributors)/(lines of code) ratio.)

> That the object is allocated at the same address as its base subobject is guaranteed by the standard, if I remember correctly.

Huh. All sources I could find seem to claim that it actually isn't, but maybe I'm looking at the wrong ones.

> Your particular assert is not, though, because long is not guaranteed to fit a pointer (and doesn't, on Win64).

My bad. I've mostly only used unixoid systems for too long now.

> printf over iostream

But printf is so much more legible when you have to format complex strings.

> passing struct or std::string to printf

Who does that?

> There's no benefit to using malloc/free whatsoever, and it forces you to cast.

I do value keeping portions of code that don't use C++ features in C for reusability purposes, and moreover there is the whole issue that it's easy to get confused about initialisation with int* a=new int (uninitialised)/new int() (=0). If you use malloc, it's clear to everyone that it's uninitialised.

> Tuple has syntactic support as of C++17:

Yes, ugly, non-principled syntactic support.

  std::tuple<int,int> a = {1,2}; // { }, like most other instances of lists of things
  auto [x,y] = a; // [ ], for some reason (not used for lists/tuples anywhere else)
  auto [z,w] = {1,2}; // this doesn't work at all
Surely being able to abbreviate B=C; A=B; into A=C; is a sane thing to expect when there is no good reason against it.

> If you ditch exceptions, you might as well ditch constructors as well, since there's no way to report errors from them otherwise. You're also forced to use new(nothrow) then. Basically, the language is designed around exceptions, and excluding them is fighting it.

I've worked with a number of embedded platforms that had C++ support without exceptions. As far as I know, there are also still issues when exceptions are thrown through non-C++ stack frames (e.g. a callback invoked from a C library). I'm aware of the problem of errors in constructors, but think that in general it is best to try and write code so that constructors don't do anything that can cause errors (I strongly prefer constructors to only serve the role of putting the object in a coherent state, and having a separate Init function for any nontrivial operations that could fail.)

Memory allocation may be an exception to this, but I feel like code where the sane reaction to OOM is not to treat it as a panic-abort condition is special enough that special measures such as an provisioning an explicit "constructed, but no memory has been acquired" state in your objects are justified.

I really do want exceptions to work - having worked with Standard ML for a long time, I'm well aware of how right they feel as a solution to error handling - but the C++ implementation of them still feels like it ultimately has way too many moving parts to be trustworthy.

(Edit: The new * italics syntax on HN is really throwing me off.)

Re:“Modern” C++ Lamentations by int_19h on Friday December 28, 2018 @11:19PM (#18781805)
> I prefer using C-style casts for brevity,

There are strong reasons to avoid them altogether in C++, not the least is that you can sometimes get a reinterpret_cast where you expected a static_cast semantically - usually because you have forgotten to include the header that has the definition of the type, and are dealing with an incomplete type (explicit static_cast will fail in that case; but C-style cast will be treated as a reinterpret_cast, even if it would have been a static_cast if the definition was visible and type was complete).

> Who does that?

The typical example is when people pass std::strings to printf, either because they expect them to work with %s, or because they simply forgot to call data(). Unfortunately, on compilers that don't try to detect structs-as-varargs, this often works by accident.