by gumby · 7y ago · 0 comments
I've really enjoyed programming in c++17 for the last three years (I had the luxury of starting from an empty buffer) and find the language pretty expressive. If you are able to use it as a "new" language, ignoring its C roots and features that exist pretty much just for back compatibility, it's really quite expressive, powerful, and orthogonal.
I'm actually pretty glad the c++ committee has been willing to acknowledge and deprecate mistakes (e.g. auto_ptr), to squeeze out special cases (e.g. comma in subscripting) and to attempt to maintain generality. Conservatism on things like the graphics standard is reducing the chance of the auto_ptr or std::map mistakes.
Expressive and powerful are definitely true, but I'm not so sure about 'orthogonal'.
Most C++ features seem to depend heavily on each other, and library decisions can impose restrictions/boilerplate on application code in many areas.
Especially as the language has evolved, features like exceptions, destructors, copy and move constructors, and operator overloading have become more and more indispensable. Template functions are still required for any kind of variance (e.g. you still can't have a non-template function that works on a const std::shared_ptr<const *base_type> or any derived type).
None of these is unbearable, but I do believe that even the modern subset of C++ is still the least orthogonal mainstream language in use (and definitely the most complicated by far). To be fair, it's also likely the most expressive mainstream language too, and still the most performant.
I guess you meant, you can't have a function that accepts a shared_ptr to the base type without indirectly using template machinery?
Because you can most definitely have a function that does this that is not a function template.
#include <memory>
#include <iostream>
struct foo {
virtual ~foo() = default;
virtual void bark() const { std::cout << "fork\n"; }
};
struct bar : foo {
void bark() const override { std::cout << "bark\n"; }
};
void poke_so_it_barks(std::shared_ptr<foo const> const thing) {
thing->bark();
}
int main() {
poke_so_it_barks(std::make_shared<foo>());
poke_so_it_barks(std::make_shared<bar>());
}If I had stuck with std::vector my point would have been better. Even though theoretically a `const std::vector<derived* >` IS-A `const std::vector<base* >`, that is, a read-only view of a collection of derived elements behaves the same as a read-only view of a collection of base elements, you can't pass the first to a function expecting the second in C++, unless you make your own function a template.
But I don't see how this could be implemented without completely changing large parts of the language.
In the one case of covariance that actually exists, overriding `virtual base* factory()` with `derived* factory() override`, the overridden function knows that the function it overrides returns a `base* `, so it can just return a `base* `, too, and callers through the subclass pointer know that they can adjust the return value back to a `derived* `.
But even the closest cousin, argument contravariance (i.e. overriding `virtual foo(derived* )` with `foo(base* ) override`) doesn't seem feasible. Callers through the base pointer will pass a `derived* `, so the overridden function has to expect to be passed a `derived* `, and there is no adjustment that can be made to a `base* ` to turn it into a valid `derived* ` statically.
The vector example is even more impossible. Since the function expects all members of the `std::vector<base* > const` argument to be `base* `, a caller with a `std::vector<derived* >` would have to allocate a new vector and adjust each individual pointer, which would be a terrible hidden runtime cost. (If they had added a constructor to accept a range to complement the one that takes an iterator pair, that's exactly what would have happened, though.)
Sadly the C++ ABIs are standardized the way that C ABIs are (I'm OK with why but it's unfortunate in that it creates a barrier) so you have to have separate libraries compiled with g++ and clang++ if you use both on your platform (we use both because they catch different bugs, and for that matter exhibit different bugs). But it means you can't simply install, say, fmt in any system-wide directory like /usr/lib or /usr/local/lib
Just as an amusing side note: Common Lisp used to be criticized for the massive size of its libraries and later likewise C++. It was true they were quite large. Now both are criticized for their tiny libraries. Which by today's standards they are.
Part of "size of libraries" is "mental size of libraries".
And C++ and Lisp and have very large mental spaces for their main core libraries. A "String", for example, carries a huge amount of mental baggage in those languages. In most other languages, a string is extremely straightforward because it was designed into the language from the start.
It's essentially a std::vector<char> with a few random convenience features bolted on.
I guess some of the confusing points are: not unicode aware, string literals aren't std::strings by default, c_str returns a pointer to a buffer with length one greater than the string length, and the usual C++ quirks like why is there both data and c_str?
I think one of the classic advantages of C++ over C is that you have the option of std::string instead of char arrays.
I don't program in C++ so I don't really know but I do a lot of pure C and the strings truly are a mess (despite being VERY straightforward)
“Modern, dependency-heavy environments” are a symptom of the fact that certain ecosystems make it easy to get addicted to dependencies; I don’t think they’re a goal to strive towards.
And not only for the libraries:
Similarly, Cargo in Rust is an absolute dream to work with, you just run `cargo new <project>` and then `cargo build`. That's it. If you want to add a dependency you can do so from the public crates.io repository or a sub-path or a git repository.
No language should be without this core feature, so it'd be great to see C++ get it too.
I already have a dependency management tool for C++; it is called the Ubuntu package repositories. I don’t need another one baked into the language.
BTW modules won't address this. I'm not sure you did but some other down thread comments implied that some people thought it would.
There is also C. The tooling and the "package manager for C++" would be expected to seamlessly work for C and be expected to be accepted and used by the C community.
(personally I use CMake + OS package manager)
The cmake language might not be beautiful, but it does allow for simple sub-projects/library scripts once the main cmake script is set up properly.
This is currently really easy to do cleanly though CMake by using Hunter and toolchain files (don't use submodules or addexternalproject)
External tools like Conan are also unnecessary bc they introduce redundancy and extra maintenance
My advice about build tooling is to use buck (from Facebook) or bazel (from Google). If you have an ex-Googler nearby, use Bazel. If you have an ex-Facebooker nearby, use buck. Otherwise flip a coin.
Buck and Bazel were created for complex internal dependencies.
You'll have just as easy/hard of a time getting Boost installed with Bazel as you would for Make.
Or publishing an accessible library that depends on Boost.
> Or publishing an accessible library that depends on Boost.
This is patently false. Here is the bazel dependency for boost (put this in your workspace file):
git_repository(
name = "com_github_nelhage_rules_boost",
commit = "6d6fd834281cb8f8e758dd9ad76df86304bf1869",
shallow_since = "1543903644 -0800",
remote = "https://github.com/nelhage/rules_boost",
)
load("@com_github_nelhage_rules_boost//:boost/boost.bzl", "boost_deps")
boost_deps()
No other installation necessary. If someone has a C++ compiler and Bazel installed that will allow you to build against Boost deps (e.g. "@boost//:callable_traits"). No downloading boost by hand, no building boost by hand, no managing it's build, bazel does all of that.Bazel does have a dependency ecosystem, it's based off of hashed versions of publicly available git repos and http archives (and anything else you want really). Which means any code anywhere can be a dependency while still being reproducible. Additionally you can provide local build instructions for the external code, so you don't even need to rely on their build. The better way is to find someone who maintains a BUILD file for a repo (or mirror and maintain it yourself) but still.
I am quoting the word "dimension", because applying a precisely defined mathematics concept to something messier (like programming) will require a certain amount of hand waving and squinting.
Perhaps it's easiest to give examples of what it's not. At first in C you could only assign scalars; to assign a struct or union you had to call memcpy() or something like it. Eventually you could assign aggregates, but you still can't assign arrays unless you hide them in structs. It took a while before you could pass or return an aggregate.
Exceptions of that sort are non-orthogonalities.
"In computer engineering, an orthogonal instruction set is an instruction set architecture where all instruction types can use all addressing modes. It is "orthogonal" in the sense that the instruction type and the addressing mode vary independently. An orthogonal instruction set does not impose a limitation that requires a certain instruction to use a specific register[1] so there is little overlapping of instruction functionality.[2]"
Its use here is more general, but I hope the specific example helps.
In describing features orthogonal is basically jargon for unrelated and adds no additional clarity imo.
I.e. you can understand one aspect of a programming language (memory allocation, generic programming, standard library, mutability, control flow, pattern matching, etc.) without understand every aspect.
As a counterexample, if a language has generics, but only generics for a standard array type, that lacks orthogonality.
1 + 2;
std::add(1, 2);
std::int(1).add(std::int(2));
That's is not orthogonal at all, since we have 3 different ways to do the same thing for no discernible reason.
An orthogonal interface is one where there are fewer reasonable ways to do something, and each function/operation has it's role clearly defined, it doesn't try to do things unrelated to its main role, and the interface doesn't mix different layers of abstraction (like intertwining OOP and arithmetic in my 3rd example, when there already are native arithmetic operations).
That example sticks with me.
- std::unique_ptr and std::shared_ptr (your code should not have any new/delete). It's easy to write code with clearly defined ownership semantics, and I've yet to create a memory leak.
- Proper memory model so that multithreading has defined semantics.
- Lots of syntactic sugar (auto, range-for, lambdas, structured bindings, if constexpr, etc.).
- More metaprogramming tools/fun.
C++11 alone is a very different world compared to what you are probably used to.
I cannot begin to describe how huge a thing this was for me. I came to C++-17 (just about) from C++-98 -- a language I hated so much, I vowed I would never, ever write anything in it on purpose.
It is a massively different beast today from what it was, but the biggest thing of all is this change in how you deal with memory. It was like going from a particularly annoying and verbose aberation of C to a particularly fast and expressive version of Python.
YMMV, of course. In fact, it may vary to the point of becoming absolutely unrecognizable if you're dealing with a massive legacy codebase. But I have to say, I've become a very big fan in the last few years.
More important in my opinion are changes to the language, like lambdas or auto.
I did the latter for a project that started around 2000 and never looked back.
But coding on C++ has become quite fun. Generic lambdas deserve much of the credit.
* Hash maps in the standard library (every so often I have to go and look it up to remind myself that no, I’m not imagining things, C++03 really didn’t have hash maps in the standard library, as ludicrous as that sounds)
* Regexes
* Option and Variant types
* Move semantics
And my personal favorite...
* foo<bar<quux>> is no longer a syntax error
std::unique_ptr<foo> m_foo;
How do you pass that into a function that can receive a pointer to foo, but does not require it? The only way to do so is to declare the function to take a foo* and pass it m_foo.get()In summary, * will never be deprecated until C++ has support for something along the lines of Rust's borrowing and lifetimes.
Many people have pointed out that C++17 has std::optional. While that's true, I don't think it'll deprecate raw pointers. I'll try to explain why.
Here's an example you can paste, compile and run:
#include <iostream>
#include <memory>
struct foo
{
int thingamajig;
};
void borrow_optional_foo(foo * borrowed)
{
if (borrowed != nullptr)
{
borrowed->thingamajig = 42;
}
}
int main()
{
std::unique_ptr<foo> owned = std::make_unique<foo>();
owned->thingamajig = 17;
std::cout << owned->thingamajig << std::endl;
borrow_optional_foo(owned.get());
std::cout << owned->thingamajig << std::endl;
return 0;
}
If you run it, it should print: 17
42
What would it look like if we wanted to use std::optional and get the same behavior? #include <iostream>
#include <functional>
#include <memory>
#include <optional>
struct foo
{
int thingamajig;
};
void borrow_optional_foo(std::optional<std::reference_wrapper<foo>> borrowed)
{
if (borrowed)
{
borrowed->get().thingamajig = 42;
}
}
int main()
{
std::unique_ptr<foo> owned = std::make_unique<foo>();
owned->thingamajig = 17;
std::cout << owned->thingamajig << std::endl;
borrow_optional_foo(std::make_optional(std::ref(*(owned.get()))));
std::cout << owned->thingamajig << std::endl;
return 0;
}
As you can see, there's a tradeoff involved. On the one hand, you get crystal clear, descriptive type: std::optional<std::reference_wrapper<foo>> is clearly an optional reference to foo.On the other hand, using it is absolutely atrocious: you have to write borrowed->get().thingamajig as opposed to borrowed->thingamajig, and std::make_optional(std::ref(*(owned.get()))) as opposed to owned.get()
Does it work? Absolutely. Is it crystal clear? Indisputably so. Will it deprecate raw pointers? I really, really doubt it, but that's just my opinion.
Same as you would have a function that can receive an `int` but does not require it. Or a receive a `std::vector` but does not require it.
I surmise that you mean "how do you pass any value (pointer or otherwise) into a function that can receive a value but does require it". And I surmise you have before used pointer indirection to pass that value because it has a conventional sentinel value of 0/NULL/nullptr.
You are correct in that optional values did not have a standardized solution, until C++17 std::optional.
If you don't have C++17, I recommend one of the equivalent third-party implementations:
* https://www.boost.org/doc/libs/1_52_0/libs/optional/doc/html...
But C++ is a systems programming language and * is still quite useful.
> I had the luxury of starting from an empty buffer
Let's assume that I'm willing to flush the cache. Are there and C++17 learning resources that you might recommend? My day-to-day languages are Python and scripting languages.The ISO C++ Standard draft (unironically—it's actually quite readable and is actually up-to-date unlike a lot of books)
Tour of C++ (book) by Bjarne Stroustrup (start here, you can read it in one weekend)
* It's gosh darn huge
* While not the hardest standard to read, it is still a standard, so has to be focused on really really low level detains and precise complete explanations instead of being a good learning resource
That said it is a great resource if you're ever confused about some corner of the language -- a lot of articles explain things slightly incorrectly.
Also the books by the person whose blog spawned this comment thread seem to be pretty good.
Is that the case? If so, how would you recommend someone go about learning c++?
As in: have the same binary? You could probably use the same object files, but shared libraries and executables probably won't work (without trickery), just because the file format is different.
Yes you can write cross platform applications though perhaps only the engine, not UI.