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.
The compiler knows where the lifetime ends. Why do the computer's work for it?
(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).)
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.
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.
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.
How come we don't see exceptions being used in serious C++ projects then (e.g. Chromium and Windows)?
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.)
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.
* 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.)