One of the things I did for safety is that all access methods of all of my containers will bounds check and throw on null pointer dereferences ... in debug and stable mode. And all of that will be turned off in the optimized release mode, for applications where performance is absolutely critical. The consistency is very important.
Whenever I get a crash in a release mode, I can rebuild in debug mode and quickly find the issue. And for code that must be secure, I leave it in stable mode and pay the small performance penalty.
Not to mention C++ does not really provide the facilities necessary for convenient, memory-safe and fast APIs[0].
And as demonstrated by e.g. std::optional the standard will simply offer an API which is convenient, fast and unsafe (namely that you can just deref' an std::optional and it's UB if the optional is empty).
[0] I guess using lambdas hell of a lot more would be an option but that doesn't seem like the committee's style so far.
if that was not the case, `optional` would get exactly zero usage. The point of those features is that you build in debug mode or with whatever your standard library's debug macro is to fuzz your code, but then don't inflict branches on every dereference for the release mode.
That's completely insane. If there's always a value in your optional it has no reason to be an optional, if there may not be a value in your optional you must check for it.
if (my_optional)
do_stuff(*my_optional);
Here's one (explicit)conditional.However if the dereferencing, *my_optional, should be safe, it too would need to perform a conditional check behind the scenes. But it doesn't - as C++ places that on the programmers hand to not sacrifice speed
if let Some(obj) = my_optional {
do_stuff(obj);
}
>However if the dereferencing, my_optional, should be safe, it too would need to perform a conditional check behind the scenes. But it doesn't - as C++ places that on the programmers hand to not sacrifice speedSo basically that turns C++ optional types into fancy linter hints which won't actually improve the safety of the code much.
I understand C++'s philosophy of "you pay for what you use" but that's ridiculous, if you use an optional type it means that you expect that type to be nullable. Having to pay for a check is "paying for what you use". If you don't like it then don't make the object nullable in the first place and save yourself the test. That's just optimizing the wrong part of the problem.
if(auto obj = my_weak_ptr.lock())
{
do_stuff(obj);
}
> Having to pay for a check is "paying for what you use". If you don't like it then don't make the object nullable in the first place and save yourself the test.The point is that I can choose _when_ to pay that cost (e.g. I can eat the nullability check at this point, but not at this point, and I can use more sophisticated tooling like a static analyser to reason that the null check is done correctly).
Is it more error prone? yes. Does it allow for things to horribly wrong? yes. Is "rewriting it in rust" a solution? No. If I want to pay the cost of ref-counting, I can use shared/weak ptrs.
C++'s optionals are less "safer pointers" and more "stack-allocated pointers" (nor to be confused with pointers to stack allocations).
do_stuff(my_optional.value())
Is also safe, it throws if the value is absent, the safety check is performed behind the scenes.But people might not want to throw an exception, so
if (my_optional)
do_stuff(*my_optional);
Must also be allowed.
The consequence is someone can also just do do_stuff(*my_optional)
No safety check is done and you get undefined behavior if the value is absent.I don't know rust so I suspect it has a language construct which c++ lacks that prevents you from doing
let Some(obj) = my_optional
do_stuff(obj);> C++ does not really provide the facilities necessary for convenient, memory-safe and fast APIs.
> You should be using a std::optional like e.g. […] if the dereferencing, *my_optional, should be safe
And once again a terrible API puts the onus back on the user to act like a computer.
if (my_optional->_has_value)
if (my_optional->_has_value)
do_stuff(my_optional->_value);
else
panic();
and the compiler knows that the second if statement will pass iff the first does.On the other hand, if the test is further away from the dereference, and perhaps the optional is accessed through a pointer and the compiler can't prove it doesn't alias something else, it might not be able to optimize away the check. However, that probably doesn't account for too high a fraction of uses.
if (my_pointer != NULL)
do_stuff(*my_pointer)For instance, the ++ operator doesn't work for std::optional. For a native pointer, you just have to know (how?) not to use it.
The point of optional types is to force you to write checks for undefined values, otherwise your code will not compile at all. In the old-fashioned style of your example, you might forget to check for the possibility of a null pointer/otherwise undefined value, and use it as if it were valid.
IMO, that’s not the same as not having optionals at all, and writing unconditional blocks left and right that may or may not operate on undefined values. It super easy to just dereference any pointer you got back from some function call in C++, without paying attention. Optionals force you to either skip the blocks, or think about how to write them to handle undefineds. Also, it’s ‘code as documentation’ in some sense, which I’m a big proponent of.
"Deliberately unwrap the optional" is the exact same thing as "deliberately unwrap the pointer", you just deref' it and it's UB if the optional / pointer is empty.
C++'s std::optional is not a safety feature (it's no safer than using a unique_ptr or raw pointer), it's an optimisation device: if you put a value in an std::optional you don't have to heap allocate it.
> It super easy to just dereference any pointer you got back from some function call in C++, without paying attention.
And optionals work the exact same way. There's no difference, they don't warn you and they don't require using a specific API like `value_unchecked()`. You just deref' the optional to get the internal value, with the same effects as doing so on any other pointer.
Edit: There are two links in the code with more info.
Rust seeds the whole state by default: https://docs.rs/rand/0.6.5/rand/
Julia seems to seed 128 bits: https://github.com/JuliaLang/julia/blob/5741c7f53c5ea443bbd7...
However, your statement seems to apply to old languages:
C# uses only 32 bits and the time for seeding: https://docs.microsoft.com/en-us/dotnet/api/system.random?vi...
Java only supports 48 bit seeds: https://docs.oracle.com/javase/8/docs/api/java/util/Random.h...
Apart from an awkward API that's hard to use correctly, Mersenne Twister which is basically the main generator has been obsolete for years (bad quality RNs, slow, huge state, ...).
(rand() % (b - a)) + a;
or Python's random.randint(a, b)
Easy to use and often good enough.This is no longer uniform, because it introduces a bias towards small numbers.
The standard library certainly is lacking things which are commonly used (say, JSON parsing or database connection), but I think this is a conscious decision (and IMO the correct decision) to include only elements that have a somewhat settled, "obvious", lowest-common-denominator semantics. There's rhyme and reason to most of the most commonly used elements that is decidedly lacking from e.g. Python's (much more extensive) standard library.
I strongly disagree. It's quite obvious that the C++ standard library does not need to add support for "common things", because they already exist as third-party modules.
In fact, this obsession to add all sorts of cruft to the C++ standard is the reason we're having this discussion.
If there is no widely adopted JSON or DB library for C++ then who in their right mind would believe it would be a good idea to force one into the standard?
And don't get me started on the sheer lunacy of the proposal to add a GUI library. Talk about a brain-dead idea.
People working on other programming language stacks already learned this lesson a lot of time ago. There's the core language and there's the never-ending pile of third-party modules. Some are well-made and well thought-out, others aren't. That doesn't matter, because these can be replaced whenever anyone feels like it. This is not the case if a poorly thought-out component is added to an ISO standard.
Without common interfaces, flexibility in implementation is much more expensive, and innovation suffers too, as new things are harder to get off the ground without existing code that they can cheaply plug into.
So instead of trying to figure out which one of the dozens of GUI frameworks to use in making a window and have it change colour, you just write it using the standard library. You want to do a HTTP request, then there will be code in the standard library for that.
It will also save work trying to figure out which third party library to use when you want to do these things locally on a small test project.
Congrats, now you're stuck with something like Xwindows or MFC or AWT.
Granted AWT wasn't great but you could still make a GUI with it straight out of the box. It allowed you to make windows and buttons and start exploring the programming language.
Like I said having a standard library option won't eliminate third party libraries, it will just provide something in the box for people to start using straight away.
That guarantee is only achievable at the expense of forcing compiler developers to maintain a GUI toolkig for all platforms. Who in their right mind believes that's reasonable or desirable?
Many C++ targets don't support IO or networking, so lets not burden embedded compiler developers with standard library bloat.
It's not obvious to me at all.
In fact, if that was a valid argument, it would be for C++ not having a standard library at all, as everything (including vectors, strings, etc) also exists as "third-party modules".
Putting aside the continuum fallacy, it's easy to understand how the C++ would be better served by having access to a collection of third-party components instead of repeating C's and even Java's mistakes.
The Boost project is a very good example, so as the wealth of JSON and XML parsers.
In fact, this lesson is so blatantly obvious that essentially all mainstream programming languages simply adopt official package managers and leave it to the community to develop and adop the components they prefer.
Java is very well served with its library. It would have been nowhere near as successful without it.
No you don't. Read the rest of the sentence you quoted :)
> (and IMO the correct decision)
Can you, from the top of your head, tell me what irregular modified cylindrical Bessel functions are and the last time you needed to use one? And yet, they were included in the standard library in C++17: https://en.cppreference.com/w/cpp/numeric/special_math/cyl_b...
In fact, pretty much any real-valued mathematical function passes the test.
The interface is settled, almost by definition since C++ functions are inspired by mathematical functions: pass in arguments, return result. Use range/domain exceptions or NaN for reporting such errors.
The semantics are obvious: compute the named function.
The interface is lowest-common-denominator: include float, double, and long double overloads.
In fact, the same or similar interface is used in almost every language I've encountered. To contrast, the same is absolutely not true of e.g. a database module. I don't think I've ever seen two alike, disagreeing over even basic things such as whether the cursor or the transaction is the basic unit of interaction.
If the goal was to create a specialized library for solving differential equations, those would be handy there. But if not, even if you tried implementing everything that you could potentially think of to implement, there are hundreds of things that are orders of magnitude more useful to have and equally well-defined and standardized—even if we limit ourselves to mathematics alone, I’d much rather see basic constants like π or e included, or quaternions, or arbitrary precision integers, or decimal numbers… or dozens upon dozens of other things before that.
But mainly, I find it impossible to maintain the claim that any general-usage language, like C++, that implements such niche functions is trying to keep its standard library small and ‘include only elements that have a somewhat settled, "obvious", lowest-common-denominator semantics’.
Why do these functions bother you so much? It can't be namespace pollution; they're under std::. It can't be that you disagree with their interface or semantics, since by your own admission you don't even know what they are.
You named some other features, such as quaternions, that you think would be better for implementors to spend their time on, but surely you can imagine someone like yourself who is tired of having to define the Bessel functions every time they start a new project, and can't imagine why the C++ committee saw fit to include something so useless and obscure as quaternions before getting to Bessel functions.
Yeah. I must have misunderstood your definition of ‘obvious’—I though you meant ‘an obvious inclusion to the standard library’, not ‘having an obvious definition’. The definition is obvious, why they should be in a standard library is not.
> […] since by your own admission you don't even know what they are
I mostly do—I studied mathematics. Or, to be more precise, I learned about them, then never used them in programming, had to remind myself what they were and even after that, I don’t find them useful enough to warrant an inclusion to the standard library. Thus, since they were included, I think that’s a good evidence of C++ committee not trying to keep its standard library concise.
> You named some other features, such as quaternions, that you think would be better for implementors to spend their time on, but surely you can imagine someone like yourself who is tired of having to define the Bessel functions every time they start a new project, and can't imagine why the C++ committee saw fit to include something so useless and obscure as quaternions before getting to Bessel functions.
The thing is, I can’t. If you use them, you want a better support for solving differential equations than C++ offers anyway, so it’s more of a ‘OK, I have this small part already implemented, but I still have to find ways of doing the rest 95%’. This, plus the fact that I’m quite certain that people using C++ to do 3D geometry outnumber people using it for solving differential equations by a few orders of magnitude—a cursory glance at GitHub showed me that the only projects in C++ that mention it are… implementations of a standard library (and forks upon forks of those).
My problems with this is that C++ is now in a very strange place—it implements some very high level, niche features, bloating the language and its implementations (the size of glibc is a practical problem) while still lacking many others, that seem much more ‘obvious’ (i.e. ‘if given an unknown language, I would be much less surprised to find them included in its standard library). In the end, I have a language that both has annoyingly big standard library and heavily relies on other, non-standard ones for quite a lot of things.
(Granted, I've written my own C++ JSON library which I believe answers all these questions in an intuitive way, following both the design principles of the C++ standard library, and the lowest-common-denominator semantics of JSON, but it's sufficiently opinionated that I doubt I could convince any significant portion of C++ users that it's the "right" way to do things. Even if it "is", demonstrating such is nowhere near as easy as it is for unique_ptr, vector, string, thread, etc., each of which are more or less the "obvious" designs given certain constraints such as RAII to which the standard library adheres.)
I work on other projects, or on my own stuff at home, and I can breathe again. I don't always need reverse iterators on a deque, but dammit they are there if I need them.
However, I have been in too much C runtime code to be entirely happy. I've seen too many super-complicated disasters, for instance the someone who really wanted to write the Great American OS Kernel but who wasn't allowed on the team, and so had to make their bid for greatness in stdio.h instead. You learned to tread carefully in that stuff, the only good news being that if you broke something it might have turned out to be already busted anyway and no harm done, philosophically speaking, I mean.
There are no good answers :-)
As such it just sounds like a mature technology which a huge adopted base and is still holding traction. Generally maturity, traction and adaptability can be considered indicators of health and not malady.
Beauty is overstated. Engineering can be art but it doesn't have to be.
Jokes aside, I use C++ daily and see it as Warty McWartface and could spend a long time ruminating about it's faults. But adapting old stuff to new boundaries is always going to be messy. Generally rewriting history creates more problems than solves them.
The good thing here is that the standard library doesn't require 'magic' to be implemented (unlike Swift where the standard library relies on hidden language hacks).
For example, since the standard library does not have a Matrix class suitable for numerical applications (or maybe it does today...) using multiple libraries each with its own Matrix class is difficult. Multiple libraries are needed since one library may not contain all numerical algorithms one may require for a given app.
This is not a problem for Google where I assume everyone is using internally written code -- but is a problem for most of us.
well, Python comes with a builtin "matrix-like" array type and yet it's not the one which is the most used in scientific computation.
Rust is still a niche language, and if its rates of adoption and improvement do not keep up, it will remain a niche language, and fade away like Ada.
I cannot imagine a serious programmer switching from C++ to Go. If you can, you have a much livelier imaginary life than I do.
> I cannot imagine a serious programmer switching from C++ to Go. If you can, you have a much livelier imaginary life than I do.
This got a laugh out of me.
For me, coming from Turbo Pascal 3 - 6, it allowed me in 1993 to use a language with a similar level of safety and language features, instead of having to deal with PDP-11 constraints.
I was always the weird kid that asked the professors if I could deliver C projects written in C++ instead, which thankfully some of them did accept.
Specially given that at my degree, C was already out of fashion by the early 90's. First year students got to learn Pascal and C++, and were expected to learn C from their introduction to C++ programming.
Only just barely at this point. It has significant projects from a lot of the largest companies (Google, Microsoft, Amazon, etc). Firefox is using it, Dropbox is using it, Red Hat is using it.
If it does, its users will have come over from Java, C#, and C.
Languages exist to allow you to define your own layers of abstractions. The language choice ideally reflects what abstractions are useful for your project.
This statement makes no sense at all. Using a third-party library that's not specified by the same ISO standard that specifies the core languagr does not create "a different language".
It just means you're actually using the programming language to do stuff.
This isn't the case even if someone uses a toolkit that relies on preprocessor tricks to give the illusion of extending the core language, such as Qt.
Meanwhile, do you believe it's hard to implement a container?
And no, adding cruft to the STL is not a one-way street. See for example the history of C++'s smart pointers.
But more to the point, your implementation might still not be as fast as the standard library one, because the standard library can make assumptions about the compiler that you cannot in portable code - what is UB to you might be well-defined behavior to stdlib authors. Thus, for example, they might be able to use memcpy for containers of stdlib types that they know are safe to handle in that manner.
https://github.com/llvm-mirror/libcxx/blob/master/include/ty...
My argument was that it was possible to implement it with standard C++.
Insufficient SIMD support in other languages, Intel only supports their intrinsics in C and Fortran.
Tools for C++ are just too good, IDEs, debuggers, profilers.
- you can’t allocate memory and then turn it into an Swift object.
- you can’t write Decodable in pure Swift (reflection isn’t powerful enough to do “set the field named “foo” in this structure to “bar”)
- reference counts are hidden from Swift code (yes, there’s swift_retainCount to read them, but that’s documented as returning a random number (https://github.com/apple/swift/blob/master/docs/Runtime.md) because it should not be used). So, if the compiler emits more reference count logic than needed in the data structure that your library uses, there’s no way to improve on it.
POCO comes to mind.
Or you have some "domain-specific" libraries like OpenFrameworks which is very nice if you are making visual art since it comes with a lot of very simple primitives to draw shapes, etc.
There was some talk about an std2, but I gather support for it is too low to be pursued seriously.
An excellent example is std::unordered_map. This type was introduced to address perf problems with std::map. But unordered_map forces closed addressing, separate allocation, etc. which limit its performance. In return you get stronger iterator invalidation guarantees but these are rarely useful. Meanwhile Abseil's swiss tables, LLVM's DenseMap, etc. illustrate what a high-performance C++ hash table could be.
I've noticed that more and more people like me have and use large alternative history "standard libraries" that add functionality, reimagine the design, and in some cases reimplement core components based on a modern C++ cleanroom. I've noticed that use of the standard library in code bases is shrinking as result. You can do a lot more with the language if you have a standard library that isn't shackled by its very long history.