C++ the Good Parts (2014)
infoq.com
infoq.com
That said, the one thing that makes C++ better than other languages is the destructor. You can see everything else added since as making destructors more useful.
(I am old enough to tell you to get off my lawn. And have one.)
However it doesn't matter how many good parts C++3000 happens to have, if some crowds insist in writing C with C++ compilers.
- the standard library design -- every object is refcounted and any code that references the object can add it to an autorelease pool, so you can't safely predict when dealloc will be invoked
- Objective C doesn't support stack-based objects
@autoreleasepool {
RaiObj* obj = [RaiObj new];
[obj autorelease];
//... stuff
}
will de-allocate at the end of the block if nothing else hold onto it, but it's obviously less neat.Plenty of SIGPLAN papers to one educate themselves about what OOP is all about.
OOP is not MFC alone, apparently those that learn languages on the trenches without referring to them, never get to appreciate the wealth of information we have available.
Not surprising, given how many misunderstand "whatever my compiler does" for what ISO actually says.
Back to STL, it makes heavy use at compile time method dispatch via template metaprogramming and lambdas (which are implemented as classes actually by the compiler.
I know this is an argumentum ab auctoritate, but you didn't really provide an argument either :)
> Yes. STL is not object oriented. I think that object orientedness is almost as much of a hoax as Artificial Intelligence. I have yet to see an interesting piece of code that comes from these OO people. In a sense, I am unfair to AI: I learned a lot of stuff from the MIT AI Lab crowd, they have done some really fundamental work: Bill Gosper's Hakmem is one of the best things for a programmer to read. AI might not have had a serious foundation, but it produced Gosper and Stallman (Emacs), Moses (Macsyma) and Sussman (Scheme, together with Guy Steele). I find OOP technically unsound. It attempts to decompose the world in terms of interfaces that vary on a single type. To deal with the real problems you need multisorted algebras - families of interfaces that span multiple types. I find OOP philosophically unsound. It claims that everything is an object. Even if it is true it is not very interesting - saying that everything is an object is saying nothing at all. I find OOP methodologically wrong. It starts with classes. It is as if mathematicians would start with axioms. You do not start with axioms - you start with proofs. Only when you have found a bunch of related proofs, can you come up with axioms. You end with axioms. The same thing is true in programming: you have to start with interesting algorithms. Only when you understand them well, can you come up with an interface that will let them work.
I have seen this a few times and have felt that "hoax" is the wrong word each time. Later he talks about OOP being "philosophically unsound", which adds some clarity to the statement. It's not that OOP or AI are made up (true hoaxes), it's that they will not accomplish (in his view) what they set out to do because they are founded on unsound bases.
I mean... in the sense in which most people use "OO language" (which is, "a language with constructs which associates a data specification with procedures"), yes. Only hardcore pure-functional algorithms written in Haskell / ML without typeclasses, or things like Prolog, Esterel (though thinking about it), and similar research languages aren't.
Once upon a time programming looked like this. https://github.com/chrislgarry/Apollo-11/blob/master/Luminar...
"Object-oriented programming: Some history, and challenges for the next fifty years"
https://www.sciencedirect.com/science/article/pii/S089054011...
Than read on BETA design for example,
Follow up with "The Art of the Metaobject Protocol",
https://mitpress.mit.edu/books/art-metaobject-protocol
and "Xerox LOOPS"
http://www.softwarepreservation.org/projects/LISP/interlisp_...
Then "Component Software: Beyond Object-Oriented Programming" (the 1st edition with Component Pascal)
https://www.amazon.com/Component-Software-Beyond-Object-Orie...
"Applying Traits to the Smalltalk Collection Classes"
https://rmod.inria.fr/archives/papers/Blac03a-OOSPLA03-Trait...
"Self – The Power of Simplicity"
http://media.cichon.com/talks/Introduction_Self_Language_OOP...
https://blog.rfox.eu/en/Programming/Series_about_Self/index....
How about this for starters?
https://news.ycombinator.com/item?id=11940050
On Understanding Data Abstraction Revisited
https://www.cs.utexas.edu/~wcook/Drafts/2009/essay.pdf
The Power of Interoperability: why objects are inevitable
https://www.cs.cmu.edu/~aldrich/papers/objects-essay.pdf
A closure is a poor man's object
http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/m...
This isn't knocking the book, I've read it and agree that it's edifying. This list is a good resource on OOP in general. It's just not helpful in the context of this thread.
Your own words, documentation and knowledge was shared, apparently you are the one not interested.
Again: Does one really, concretely, have to read The Art of the Metaobject Protocol, a book about Lisp, to evaluate this claim about C++? Having read the book, I would say no. Which is why I say that you are evading a real discussion.
(And for that matter, it would be interesting if you fleshed out your counter-claim -- "Other than the classes used to implement all those STL concepts." -- in a bit more detail. Are you saying that all uses of C++ classes are OOP? Or that only certain uses are, but that the way classes are used to implement the STL fall into this category? Will I find the answer to these concrete questions in The Art of the Metaobject Protocol?)
Definitely, any use of class constructs with data members and member functions is OOP.
Any use of data members inside class constructs represents aggregation and if any member function on a data member happens to be called, as means to help a member function to do their work, that is delegation.
Any template implemented as class that uses its type parameters to decide at compile time what gets called, makes use of dynamic dispatch decided at compile time.
If you prefer we can pick any random STL type and dissect all their uses of OOP features, lets start with something like std::set?
Definitely not.
OOP requires, also, runtime binding and polymorphism. You can get the polymorphism by inheritance, delegation, or what-have-you. You can get runtime binding with a vtable or a name lookup.
The usual term for just-encapsulation is "object-based". The STL is definitively not object-oriented, according to its author, Stepanov, who has said that giving the STL classes member functions was a mistake.
OOP is a niche technique. It has uses, sometimes. More often, a function pointer suffices.
Object based languages are part of the OOP universe from CS point of view, plenty of literature, that apparently is too much to ask to read about, some of which I have provided above.
So here we go about std::set and it being OOP.
1 - class set, a means for encapsulation, with most of its members de
2 - Uses delegation for memory allocation via the allocator_type
3 - Uses delegation for key lookups and value comparisasion
4 - Implements the concepts Container, AllocatorAwareContainer, AssociativeContainer, ReversibleContainer alongside their respective concept dependencies, which in OOP speak are protocols/traits/categories;
5 - The actual types used for comparisaion and allocation are instances of the respective protocols, with dispatch being decided at compilation time of std::set uses, given the respective implementations as type parameters, in a way similar to multi-method-dispatch.
As bonus here is a simplified UML diagram. It isn't more detailed, because my patience to draw ASCII art is limited.
-------------------------------------------------------------------------------------------
|std| |
----- |
| __________________ |
| | <<protocol>> | |
| | Container | |
| |-----------------| |
| |-----------------| |
| |-----------------| |
| | constructor | |
| | copy-constructor| |
| | destructor | |
| | begin() | |
| | end() | |
| | cbegin() | |
| | cend() | |
| | swap() | |
| | size() | |
| | max_size() | |
| | empty() | |
| ------------------- |
| /\ |
| -- |
| | extends |
| | |
| ______________ _______________________ _______________________ |
| | <<protocol>>| | <<protocol>> | | <<protocol>> | |
| | Allocator | | ReversibleContainer | | AssociativeContainer | |
| |-------------| |----------------------| |----------------------| |
| |-------------| |----------------------| |----------------------| |
| | constructor | | rbegin() | | key_comp() | |
| | destructor | | rend() | | value_comp() | |
| | allocate | | crbegin() | |----------------------| |
| | deallocate | | crend() | /\ |
| | max_size | |----------------------- -- |
| | construct | /\ | |
| | destroy | -- implements | |
| --------------- | | |
| /\ | | |
| -- | implements / |
| | \ / |
| | implements \ / |
| | \ / |
| | \------------------ |
| | | |
| | | |
| | ------------------ |
| ---------------- | <<protocol>> | |
| | allocator<T> | uses | set | |
| |---------------|<------------------------/\|------------------| |
| |---------------| \/| constructor | |
| | destructor | |
| | begin() | |
| | end() | |
| | cbegin() | |
| | cend() | |
| | rbegin() | |
| | rend() | |
| | crbegin() | |
| | crend() | |
| | operator= | |
| | get_allocator() | |
| | empty() | |
| | size() | |
| | max_size() | |
| | clear() | |
| | insert() | |
| | emplace() | |
| | emplace_hint() | |
| | erase() | |
| | swap() | |
| | extract() | |
| | merge() | |
| | count() | |
| | find() | |
| | contains() | |
| | equal_range() | |
| | lower_bound() | |
| | upper_bound() | |
| | key_comp() | |
| | value_comp() | |
| ------------------ |
|-----------------------------------------------------------------------------------------|Concretely, you cannot take a Container pointer and point it at a std::set. You can take a T, and bind T to std::set at compile time; but that is Generic Programming: analogous, in some ways, but not the same.
In the '90s it was fightin' words to say "X is not Object Oriented", because Object-Oriented was taken as a high-status way to say Good, and "Not Object-Oriented" translated implicitly to "Not Good".
But in our brave new world, object-oriented is but one design discipline, and we have others, and enough language primitives to construct our own disciplines by mix-and-match as problems dictate.
And, I have myself simplified code that had used a virtual function to use, instead, a function pointer, and it was (still) Good. Better, even.
What renowned SIGPLAN or IEEE paper states that runtime binding is required for 100% of all OOP programming languages ever created and polymorphic dispatch at compile time doesn't count?
Changing the definition would be moving the goalposts. A new definition deserves a new word.
In Rust, generic code is fully validated as it should be, with all trait bounds being matched where need be. So you would rarely end up with needing to figure (at compile time) whether generic type T is an enum or not - because it wouldn't allow you to do anything extra with it out of the box. In Rust, an idiomatic way of adding different behaviours based on the kind of the generic type would be using traits still - e.g., you can have multiple impl blocks on your generic type, each one having different trait bounds on the generic parameter, like - if T: Copy, then implement these extra methods; standard library has tons of examples like this. The only exception that comes to mind is proc macros - when you deal with Rust code in AST form and generate new code at pre-compile-time phase, but that's a completely different story and not really related.
Indeed Rust proc macros, or Rust macros in general, are a better analog to C++ templates than Rust generics. They aren't quite the same, as during evaluation time C++ can do a bit more, and apparently type_traits is an example of what C++ can do statically. Rust's model is different, it wants macro expansion to be done by the time it starts even resolving any non-macro paths, let alone type checking or anything.
That being said, you'll be able to emulate something like that once specialization lands (hopefully also included by min_specialization).
Mind you it probably has very little real world usage right now..
Concepts aren't as powerful as Rust traits in that they are static dispatch only, while Rust supports both static & dynamic-- but they should make for cleaner code than <type_traits>
There are plenty of OOP flavours, just like there are plenty of FP flavours.
If one considers 100% Haskell's features as must have for a language to be considered FP, then OCaml and Standard ML are going to have a hard time to be considered FP.
Rust is deliberately a weaker language for expressing library semantics. You can write libraries in C++ that cannot be written in Rust, that encapsulate semantics that cannot be captured in Rust. C++ library writers do, routinely. The C++ Standard Library has many components that could not be coded in Rust, that make the language more powerful for all users.
This makes Rust easier to learn, but it limits the libraries you can use, having learned it, and limits the libraries you can write.
This is a difficult tradeoff for any language design. Haskell is more powerful, too, and also harder to learn and to use well. (At the same time, its lack of destructors also limits it in ways that Rust and C++ do not suffer.)
The OOP -- inheritance, and virtual functions -- is a niche feature that is sometimes useful, but can often be emulated well enough with function pointers.
If it's implementation inheritance, then that was never a requirement for OO, seeing how prototype-based OO has been around for a very long time.
As an example of why this matters, I’ve got a class called TimeCapture in a project. If I want to instrument how long a block takes (full function, inside of an if, etc) I can add `TimeCapture tc(“my-metric-name”);` to the block and know that the destructor on that object will be called precisely at the end of that block (capturing the end time of the block)
I don’t know the rules for Swift or Ada or OP, but I’m guessing they’ll vary.
Not true. They run when the object is deallocated. In CPython if the object is not involved in or referenced from a cycle, that’s as soon as it goes out of scope: the ref count goes to 0 and the object gets deallocated.
This is trivial to check: create a structure with a noisy __del__ and create an instance from a function, call the function, del will run. The GC has no reason to run at this point, there’s no allocation requiring any sort of reclamation, but if you don’t trust that you can just `gc.disable()` and observe… the exact same behaviour.
That's a CPython implementation detail, not a guarantee that you can rely on.
For example, both PyPy[0] and Jython use tracing GCs where this is not true.
[0]: https://doc.pypy.org/en/latest/cpython_differences.html
Which would be why I specifically wrote « in CPython ».
And it still makes the original assertion completely incorrect. Python destructors do not run « down the road, during the next GC cycle ». They may, in certain cases or implementations.
> implementation detail
There is no guarantee that even CPython will keep the current behaviour. Ultimately, the promise you're given is that __del__ might be invoked by the system some point between "the object has no live references" and "never".
The original assertion gives a much closer intuition than your description of the current behaviour.
The original commenter made a specific assertion. I demonstrated that their assertion is not true.
It seems to me that there must be some other language that would have the c++ guarantee, but I don't know of it. (it isn't hard to implement, and c++ is well known enough that other languages designers can consider the pros and cons and surely someone else has decided it is worth it)
Rust's Drop[0] has basically the same guarantees as C++: the destructor will run right before the memory is freed (although it is possible in both cases to also leak both). Combine with Pin[1] if you need the exact memory location to be stable as well.
> it isn't hard to implement
Sadly, it's basically incompatible with tracing garbage collectors, since they make it completely unpredictable when the destructor will run.
So if you ever want to allow yourself to switch to tracing GC then you'll either have to disallow it completely, or bury it in a hidden corner of the docs with a load of caveats (like Python or Java). And in the latter case you'll still have people like the GP stumble upon it, say "oh, this looks neat", and set up a really painful trap for their future selves.
[0]: https://doc.rust-lang.org/stable/std/ops/trait.Drop.html
[1]: https://doc.rust-lang.org/stable/std/pin/index.html#drop-gua...
"Finalize" on objects of type "Ada.Finalization.Controlled".
I mean, yes, those words are in there, but I'm responding to your words:
> Ada does not have destructors or anything analogous.
Which are factually wrong. Finalize is called automatically (per the link). And they are exactly what you say Ada lacks, analogues of destructors.
Your complaint, now, is that Finalize and Initialize don't automatically call the same functions in the parent. That's a separate issue, and doesn't demonstrate that Ada doesn't have this thing (a variant of destructors) which it very clearly has.
Apple seems to think that anything that you put in dealloc should end up in the system (like unsubscribing from notifications).
C++ is a dangerous, powerhouse systems language. I think it really needs things like destructors, and I’m glad to see its continuing development.
Apple is amping up KVO, in general, which I like.
The same issue occurs in c++ if you're sloppy with shared_ptr. If you know what you're doing, you can break cycles with weak references in either language. Where Python has diapers, c++ has footguns aplenty.
But if you provide a non-deterministic mechanism on top of refcounting to break the cycles, and destructors aren't consistently deterministic already, why even bother with refcounting at all?
It is possible to contrive a graph data structure with cycles, but it is a bad (i.e. slow) representation not useful in production.
Or in the "PHP has no destructors"? - in that: PHP's object model is an "interesting" mixture of Java and C++. In regards to C++ it has detemrinsitric destructors, which enable RAII. The only complication is that all objects are reference counted (like shared_ptr in C++) and one can easily lose ownership from where one expects it to be. However if you keep an eye on ownership you can rely on reference count being decreased on function exit (be it regular exit or exception) and the destructor being called, in LIFO order as one expects. This isn't used much in PHP as you don't have to manage resources as often as with other languages/domains (in short lived request world one doesn't care whether a database connection is destroyed on function end or only on request shutdown, memory is handled automatically, etc.)
C# has "using", Java has try-with-resources, Python has the "with", etc. - all of which support RAII patterns.
std::unique_lock<std::mutex> foo();
The unlocking of the mutex is then tied up with what you do with the returned mutex locker e.g. if you ignore it then it will be unlocked at the end of the current statement, if you assign it to a local variable (and don't move from that) then it will be destroyed when leaving that enclosing function, or you return it from that enclosing function to extend the length of the lock still further.You also can't compose those mechanisms so easily. For example I could make a class with a std::unique_lock<std::mutex> and a pointer to the data it protects and pass that around.
That is something that you actually need rather frequently. For example a db transaction wrapper might want to rollback instead of commit if we leave the block via an exception. You also want the "destructor" of that block to raise if the transaction can't be committed.
The only thing that the c++ method does really well is memory management (e.g. unique_ptr), because free() can't fail. But that use case is of course not a thing in gc languages.
Regarding the composition: Everything that's not memory management usually has side-effects and often wants to do something with regards to exceptions. So it's a good thing for the caller to know that the "RAII" is happening. Allowing you to complete hide that in your class is not a benefit.
C++ paints a distorted picture here, because its method is great for memory handling issues, but only OKish for everything else. But most of your RAII issues in C++ are memory related, so you don't notice the problems that much.
the difference is that with Python, the programmer can forget to use "using". In C++, as soon as you instantiate your variable on the stack somewhere, you know that ~T() will happen unless you get a segfault...
> For example a db transaction wrapper might want to rollback instead of commit if we leave the block via an exception.
I'd say that a transaction wrapper would have an explicit commit method which applies the transaction and "empties" the transactoin object - destructor would always rollback if there is something that was not committed - and if commit was called then there is nothing to rollback anymore so ~T() does nothing.
@contextlib.contextmanager
def get_a_locked_thing():
with lock:
yield thing
and then with get_a_locked_thing() as thing:
do_stuff_with(thing)
Exiting this "with" block causes get_a_locked_thing to resume at its yield statement, which exits that "with" block, which releases the lock. Throwing an exception also exits the context managers.If you were to try omitting the "with" statement and running, say, "thing = get_a_locked_thing()", the function hasn't executed yet (because you haven't entered the context manager), meaning that not only is 'thing' the wrong object, you also haven't even gotten the lock yet. So you won't deadlock/leak the lock, and you will notice in the most basic of tests that your code isn't doing the right thing.
I do agree that this is nowhere near as nice as having an object in a local variable, because "with" adds an extra layer of indentation, and that's an advantage of C++/D/Rust-style RAII. But it's definitely doable in Python and pretty idiomatic.
Yes you can use a Python context manager (that's what you're referring to) to lock a mutex, but you can't pass that context manager as a return result of a function and be sure its __exit__ method will be called appropriately in the three situations I mentioned (immediately if result thrown away, at the end of the function if stored in a local variable, later still if returned from that outer function).
In fact I don't think you can return a context manager from within a "with" block at all, even accepting that the parent function will have to manually reuse it in another with block, because its __exit__ method will already be called in the inner function. Technically this is true in C++ too of course because the object in the inner function will have its destructor called, but its move constructor will be called first giving you an opportunity to clear out its internal state (this is why my example used a unique_lock rather than a lock_guard). Things are even better in Rust: the bytes of the object are directly copied to the new object's footprint and the original destructor isn't called, so you don't even need to set up a dummy "empty" state.
> The only thing that the c++ method does really well is memory management (e.g. unique_ptr), because free() can't fail.
Mutex unlocking usually can't fail (and if they do, there's usually not much you can do about it). Same with closing network connections. Closing files can fail, and for some programs it's very important to know when that happens, but for many others it's not important at all. Python's chained exceptions are very nice, but not so important that their absence from C++'s exceptions (or Rust's panics) makes those languages useless.
There is now enough introspection in the language to actually implement implicit commit in a non exceptional path, but I think it would be a mistake.
auto my_leaky_mutex = new std::unique_lock<std::mutex> {foo()};
Yes, I am making it fail on purpose, but copy-paste in enterprise codebases does wonders for code quality.I don't know what processes Google uses for the Android codebase, but in the main code base make_shared has only been available for a little while. Today, "new" is smell that should be caught in code review at Google. When was this committed?
So what to be expected by those companies that hardly have such a deep knowledge about C++ among their troops?
This is pretty much what we do in our code base, except that the class has lock(), tryLock(), etc functions that take a lambda. The functions acquire/try to acquire the mutex and then pass a reference with appropriate const-ness to the lambda.
RAII naturally composes because a container has to clean up its memory, and it has a well defined lifetime.
Python has a very straightforward model for its context managers, two magic methods:
def __enter__(self):
...
def __exit__(self, etype, eval, tb):
...
To handle many resources being released, the stdlib prefers a more direct approach using a special class: with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
And it makes sense. You probably don't want regular containers to have yet another magic method defined on them, and there is no clear single behavior the a container's __enter__ and __exit__ method could have.And it doesn't compose in other ways. In async code, for instance, there's a completely separate mechanism with `async with` that calls __aenter__ and __aexit__.
It really comes down to the fact that when objects have an ambiguous lifetime, which is a consequence of garbage collection, you can't have RAII.
https://android.googlesource.com/platform/frameworks/base/+/...
they should have used make_shared, but it is still safe
It exposes everything as C APIs, even thought it is a mix of Java and C++ on the implementation side, leaving the C++ developers to write their own type safe abstractions from scratch.
Most just can't be bothered and write C in C++.
Then there is the whole issue how, following Google C++'s guidelines, the NDK is actually implemented.
I don't know how much back in the past it is, but pretty much every time in the last ten years I tried to beat a C++ abstraction, I almost never managed to substantially improve (and since gcc.godbolt.org exists it made it much easier to witness that most of the abstraction layers entirely disappear at -O2)
Or they may not see that stuff as an improvement in the first place (e.g. see Orthodox C++[0]).
Discomfort is not a valid reason to avoid learning new things.
That seems like a rather weak conclusion given all the words that preceded it. You might as well just start and end with this:
New standards have issues, people don't know how to use them correctly, and compilers are slow to catch up. Wait 5 years to use a standard so all these things are worked out, and you don't have to worry about the details that don't stick.
In any case this is just an example, there are a couple of similar "subsets" with the same idea of keeping C++ use to its bare minimum, it is just that i remember this one because of the name :-P
Thing* thing = new Thing();
thing->DoStuff();
delete thing;
is perfectly valid C++ and has been since the invention of the language. It's not a good idea, but it is valid.If, OTOH, you do
Thing* thing=(Thing*)malloc(sizeof(Thing));
free(thing);
the you fully deserve the inevitable world of pain that is coming your waywe're in 2020.
$ clang-tidy -checks='cppcoreguidelines-*' foo.cpp
/tmp/foo.cpp:10:3: warning: initializing non-owner 'Thing *' with a newly created 'gsl::owner<>' [cppcoreguidelines-owning-memory]
Thing* thing = new Thing();
^
/tmp/foo.cpp:12:3: warning: deleting a pointer through a type that is not marked 'gsl::owner<>'; consider using a smart pointer instead [cppcoreguidelines-owning-memory]
delete thing;
^
/tmp/foo.cpp:10:3: note: variable declared here
Thing* thing = new Thing();
^I'm not arguing it's good C++, but saying "C++'s destructor behaviour doesn't work if you don't use C++" in relation to using new and delete is clearly nonsense.
I guess it depends on your definition of "valid".
Let's say we have:
class Thing
{
public:
Thing() { cout << "created" << endl; }
~Thing() { cout << "destroyed" << endl; }
};
Assuming the happy path, the new/delete version will be functionally identical to a more correct/idiomatic {
auto thing = make_unique<Thing>();
}
The malloc/free version won't call the destructor, and therefore doesn't do what a "normal" object would do.It's splitting hairs, I guess, but that's where I'd draw the line.
[1] if you are implementing something like a container and dealing to raw memory you might need to call destructors of subobjects explicitly, but because it is needed to correctly reclaim memory, it is almost always done and all standard containers do it already. On the other hand in python list doesn't implement the context manager protocol.
RAII is strictly more powerful and more regular than context managers.
If you think other language X supports RAII, you don't really understand it. It's not really compatible with obligate-GC. Finalizers, in particular, are not it.
The thing about destructors is that reclaiming memory is only their most trivial use. In C++, as in D and Rust, and Haskell, too, catching errors is the type system's most trivial use. It does the heavy lifting.
If your program isn't putting the type system to work, you're toiling away with a screwdriver while people around you are using impact drivers and forklifts.
Not as safe as proper RAII but very useful at the site of declaration to write scope(exit) close(file); or similar
Further, Rust has destructive move, making drop even more flexible.
RAII is associated most prominently with C++ where it originated, but also D, Ada, Vala, and Rust.
https://en.wikipedia.org/wiki/Resource_acquisition_is_initia...
Topical sidenote D's got destructors as well:
With C++ RAII you can have a brain fart and forget about freeing a resource, but you're still OK.
This doesn't work with lexical-scope-cleanup things like golang's defer (and bugs me when new languages add it instead of destructors). Instead you either have to document that the caller has to remember to defer-cleanup the result, or you have to do funky things like take a callback that receives the value, invoke the callback and defer-cleanup the value.
What makes C++ flexible in practice is move semantics, which lets you move-return values, such that only the destructor call on the caller side is the one that matters.
Notice how I said "cleanup-via-destructor" rather than just "destructor", for this reason.
Disclaimer: Not a language lawyer, just a fan.
No, exceptions are not the answer. NONE of the C++ projects I've worked on in the last 30+ years have used those in production. Exceptions are far, far worse trap.
It's funny that the teams across half a dozen companies I've been in have independently come up with just about the same set of guidelines about C++ features. It's almost like some of those features were bad ideas. :-)
On the other hand, this is exactly the problem that arises if you refuse to use exceptions, because then the constructor has no way to signal that it failed. Since constructors, by their very nature (acquiring resources, validating initializers etc), can fail, you have to resort to "is it valid?" flags, and your API clients have to check those flags or risk unspecified behavior.
Take a look at the Google C++ guidelines, as an example.
https://google.github.io/styleguide/cppguide.html#Exceptions
They're fine in other languages (python, etc.). Note that golang does not really have them, except in a very crude sense.
I will also add that, from my past experience working on codebases that didn't or couldn't use exceptions (e.g. across C ABI boundary), the lack of exceptions, and people forgetting to check error codes, or propagating them improperly, was a very common source of hidden bugs.
This is a wholly false statement. Exceptions are used almost everywhere C++ is used. Google is a peculiar outlier, and suffers for it. You can read right in the cited document why they were obliged to give up using exceptions. It imposes huge costs which Google happens, by virtue of monopoly status, to be equipped to afford.
Not quite. The syntax has become even more weirder and the language more complicated. I really do think that the standards committee have gone overboard adding in everything and the kitchen sink. The pace of change has been crazy for such a old and widely used language. The standards committee should just disband for a couple of years and go take a rest instead of adding in everybody's "favourite features" :-)
> The pace of change has been crazy for such a old and widely used language.
Not necessarily a bad thing, at least you can request specific standards at compile time so you can stick around at whatever standard you want and it should work for a very long time (there's still C++03 and older out in the wild), and those who want the features in the latest standard can upgrade.
The good thing about the STL additions is that you can simply ignore them, as they are not part of the core language, just like people have ignored iostreams since the 90s.
I think a lot of things were added in just to "get away" from C roots and make C++ its own language which IMO was a bad idea. For me, C++ is first and foremost a "better C with Classes" because i can keep that subset of the language in my head easily.
PS: Relevant other HN discussion: https://news.ycombinator.com/item?id=24649992
Anyway, it is true that C++ is not fully backward compatible, some things have changed in very important ways, but the vast majority of the code will compile unchanged and breakages should be caught at compile time.
Not specific to C++, but I'm definitely loving the addition of coroutines to the language. It makes multi-tasking a lot more clean especially for something like userspace networking.
I consider myself quite proficient at C. I wrote quite a bit of C++ from 2011 to 2014, while I was ramping up at programming. C++11 wasn't really a thing back then in my experience. The new features are really nice, but the syntax truly feels alien to me.
I am now looking forward to learning Rust, which seems more cohesive in general, and less of a bag of weirdly shaped features. Meanwhile, I'll probably keep on using C++ as "C with classes" when I have to. And I feel like codebases have to pick a subset of C++ they are comfortable with to be approachable to outsiders.
What modern C++ really needs is a rebranding. Something like "C22"/"CX"/"Z" to distinguish itself from old C++. Together with a guide on what the safe features and "unsafe"/deprecated features are the developers could get new certificates to prove that they are up to date. Companies/management could easily require that the new C++ is used and developers are actually capable. (This organizational issue is IMHO the most important part.)
https://docs.microsoft.com/en-us/cpp/code-quality/using-the-...
but yeah, there is more to that and I doubt C++ can be fully unsafe unless you set references and pointers (they can be invalidated) probably many other things as unsafe. c++ is unsafe by design
If you're in the former group you'll be delving into all the template nitty gritty. If you're in the latter group you'll rarely need them (I think our 200k+ LOC C++ codebase uses std::enable_if three times).
I still like the language though. There's no obligation on any C++ dev to use all the new features.
Personally, I find Rust's syntax to be quite ugly compared to C++'s; horses for courses I suppose.
It’s a puzzle. One can only conclude that secretly C++ programmers like all the new feature whilst complaining bitterly about them in public.
The language is almost totally unprincipled in my opinion so you just have to know the minutiae to reason about and work with novel constructions.
In the hands of an expert, it's an awesome tool. To me, it's a miserable chore.
Nah, couldn't be! It's just C++'s fault, surely!
> I am now looking forward to learning Rust
Prepare yourself. I personally think one of the major downsides to learning Rust is how quickly the language is moving.
I first started looking into Rust in ~2015, but it seems most hobby projects from that time won't even compile today.
It feels like there are non-breaking changes to the language almost weekly. I still cannot figure out if I should be using nightly rust, stable rust, or switching back and forth depending on the project.
Overall I think Rust is doing a lot of great things, but I'm not sure it is handling the "mess of features" aspect of programming languages particularly well.
Do you think anyone dropped into a foreign code base of Java 15, C# 9, PHP 8, Python 3.7, C2X will be able to understand all of it?
2 major language revisions have been released since this was recorded.
for(const auto& item : dummy_list) { ... }
It was fucking ugly and verbose use iterators for something so basic and simple.
std::sort(my_container.begin(), my_container.end());
I mean, yes, in 0.1% of all cases I would want to sort something that is not an entire container, and for that it's great that this exists. But for the 99.9%, why isn't there an overload that would allow me to do: std::sort(my_container); for (int i : ints | std::views::filter(even) | std::views::transform(square)) {
std::cout << i << ' ';
}
notice the `for (int i:ints)` and the pipes filters.EDIT: more specifically, you can use sort on a range now (source : https://cppreference.com):
ranges::sort(s);Documentation here: https://en.cppreference.com/w/cpp/ranges.
They are called "range adaptors" (weird naming IMHO).
[0] https://www.boost.org/doc/libs/1_72_0/libs/range/doc/html/in...
The committee is very reluctant to break old code. That's one of the reasons the language as documented is so large.
That being said it's not clear to me what would have broken by putting sort(x) into std:: as you recommend.
template<typename T> void sort(T& t) {
std::sort(std::begin(t), std::end(t));
}First, at the time the language did not have enough forwarding capabilities, so you would have needed a lot of overloads to handle const and non const containers.
Second getting anything approved in committee is a huge effort so often proposals are stripped to the bare minimum; in particular the STL was already huge and Stepanov tried to include only what he thought were the fundamental components.
The new ranges have been in development for almost 10 years (arguably they suffered a bit of mission creep), so it is not just a matter of adding range overloads for functions.
What would otherwise be a trivial one liner with something like transform suddenly turns into a 3 line call
I remember talking with one of the world best HPC expert and he said that it's the most advanced language today when it comes to optimisation. Don't know if that still applies.
A question while we are at it:
// Am I the only one left on this planet using this style of bracketing:
void foo()
{
cout << "brackets like that are more readable!" << endl;
}I wrote quite a lot of HPC-like code lately. Can confirm.
The reasons include first-party support for hardware intrinsics on all platforms (SIMD is the most important, but also scalar stuff like popcnt, pdep/pext, etc.), full control over RAM layout which allows to optimize data structures for cache friendliness, and the ecosystem of high-quality third party libraries.
BTW it was him: http://www.theochem.ruhr-uni-bochum.de/~legacy.akohlmey/inde...
I also write a bit of Rust and I find Rust's nagging me to use the "default" brace style annoying.
IMO this is very much a personal taste issue, it depends on how someone grew up learning to read, what programming languages they grew up with, etc.
This is from 2014 so although it's useful it doesn't quite qualify. The other sources I can find are either even older, or they're tutorials about very specific features with a very narrow scope.
Bjarne Stroustrup's "A Tour of C++" (2018) is also frequently recommended.
I haven't worked with C++ for years, and it's nice to see there really has been some progress improving some of the C++ parts.
That article covers the big four new features:
- concepts
- modules
- coroutines
- ranges library
It mentions that modules will improve compilation times. How are compilation times these days? That was one of my least favorite aspects of C++ back in the day.
https://devblogs.microsoft.com/cppblog/standard-c20-modules-...
https://devblogs.microsoft.com/cppblog/introducing-vcperf-ti...
https://devblogs.microsoft.com/cppblog/improving-code-genera...
https://devblogs.microsoft.com/cppblog/profiling-template-me...
https://devblogs.microsoft.com/cppblog/faster-builds-with-pc...
In general, I tend to wait less for my C++ builds than Rust ones.
It is possible to have a fast C++ build, but it still requires diligence, ie avoiding including massive headers everywhere & using lots of forward declarations etc.
Many code bases don't do this so they end up with ~forever builds.
(scnr)