67 points · by joboccara · 8y ago · 86 comments
I mean, even RAII was already a thing in MS-DOS C++ code bases.
However, many kept using it as if it was C with some extras.
Never mind compiler support. I just recently noticed with delight that I finally forgot the exact VC #pragma numbers to disable all the STL warnings. Which gives me hope that one day I'll manage to do the same to ORA-00907.
MFC wasn't something I would list as good C++ GUI examples.
Unfortunately Borland just made a mess of their customer base.
Even today, Visual C++ is not as visual as C++ Builder.
struct { int a; int b; } x { 1, 2 };
auto [b, a] = x;
Now b is 1 and a is 2, even though in the original structure b was 2 and a was 1. This is contrary to how most other languages with this feature behave.(I wrote a bit about this once: https://thebreakfastpost.com/2017/11/15/c17-destructuring-bi...)
I haven't had the opportunity to write any C++17 in production yet, so I'm not sure how dangerous this dangerous-looking thing actually is.
The b and a in "auto [b,a]" are arbitrary names you are applying to the result of the destructuring assignment, and they are essentially unrelated to the names of the struct members.
If you write "auto [apples, oranges] = x;" it means exactly the same thing as [b,a] and [a,b]: two ints, each with an arbitrary identifier, the first with value x.a and the second with value x.b.
The only unusual and slightly flaky thing that's going on is interpreting a struct as a sequence; the order of struct fields is usually relevant for its memory layout, but not for language features that use identifiers.
What you appear to want is something entirely different: constructing something that automatically mirrors the names of the struct members.
For example Java reflection allows enumerating the fields in a class, getting their names and other metadata, and extracting from an object the value of a field of its class. You could then populate a map with a destructured copy of an object in which each value has the same name as in the original object.
I do get what you're saying; I can see why it's done this way. C++ lacks tuples at the language level, so there is no other way to do an anonymous tuple-style binding. Being forced to bind to the same name as the structure element would be inconvenient for various reasons. It makes sense. I just think it's problematic that changing the declaration order of a struct can silently break code that uses it. And it is different from other languages - not just natty ones like ML but also mainstream ones like Javascript ES6 - which makes it a point of some curiosity.
> What you appear to want is something entirely different: constructing something that automatically mirrors the names of the struct members.
It's all just a question of declaring and assigning local variables, there would be no mysterious objects or runtime reflection involved in either case.
I realise that C++11 structure initialisation syntax already blurs this distinction. That's already a bit dangerous in my view, although in both cases I can understand why they chose to do it that way.
Are there other languages in which struct (not tuple) bindings happen by declaration order?
I've always flat-out avoided C++ because I don't think I will be able to handle memory management for a large program; It'll be riddled with security holes and memory leaks.
Unfortunately, many OSS programs I want to contribute to are written in unmanaged languages like C or C++. As far as I'm aware, it's easier to get memory right in modern C++ compared to C, which hasn't received many updates.
- Never use C style strings or arrays directly.
- Prefer STL data structures for memory management (unique_ptr , shared_ptr and others)
- Don't use C style enums (class enums are type safe)
- Don't use C casts
- When dealing with C libraries, always wrap them in safe C++ wrappers with safety invariants
- Always enable bounds checking for vectors, strings and iterators on debug builds.
- Always use references for pointer parameters that aren't supposed to be null
- Make effective use of RAII
Basically all boils down to don't program in C++ as if it was C with extras.
No. The modern C++ features like std::unique_ptr and std::shared_ptr replace old patterns of "malloc()/free()" and "new/delete". This ensures correct cleanup and avoids leaking memory.
However, there are other topics of "memory safety" such as preventing runtime behavior of buffer overruns and writing to invalid pointers. The virtual machines like Java JVM and C# CLR create a constrained memory area with extra runtime checks and the new C++ language features don't replicate that type of memory safety. Also, those "managed" languages don't expose raw pointers as a 1st class programming feature (e.g. don't use "unsafe" blocks) so that in itself creates an environment of extra memory safety.
Although shared_ptr does open you up to a whole new class of bugs, with circular references causing memory leaks and object lifetimes being harder to reason about, especially in a multi-threaded environment.
I agree in general, though, things are a lot better.
I would not say completely safe if we only consider the language, but on the rare occurence of a memory bug, usage of asan / ubsan of GCC and Clang (both have different sets of checkers), -D_GLIBCXX_DEBUG and clang-tidy, it's frankly impossible to have this kind of bugs. Just running by default with -fsanitize=address -fsanitize=undefined will help you to trivially eliminate so many bugs it's not even funny.
However, you fight the language much less than in Rust in my experience, and if you don't do memory allocations directly but instead use <vector> and others it will be a breeze.
Sanitizers still have some issues with them.
Yes. Just don't use raw pointers. Use unique_ptr, shared_ptr and weak_ptr instead.
Just off the top of my head smart pointers do not protect against:
- null pointer dereferences
- out of bounds array access
- iterator invalidation
- dangling (non-owning) references
C++ sort of has a reputation for compilers omitting messages that are, to put it mildly, unhelpful and verbose. While they’ve improved over the years, I’d like to know if new features have new confusing error messages.
Saving 30 seconds writing a one-liner doesn’t really “count” if there’s a chance of seeing a 40 line template-unrolling when deduction fails due to a typo. Does that happen here?
Compared with Python, say, where you always know that the burden of understanding how a variable is used is part of the reader’s responsibility, maybe with conventional help in docstrings or optional type hints, this C++ feature seems like the worst of both worlds. You still have to add some annotation (“auto”) and keep in mental cache an understanding of the types, instead of just being nice and explicit about it and declaring things with the types.
So you don’t get the freedom of duck typing on the auto’d variables, and you trade for slightly reduced syntax instead of explicit annotations for the reader.
It seems like it would immediately become a C++ anti-pattern to use structures binding. It’s cute instead of pragmatic.
Your perspective is that type annotations are there for the reader. I agree with tzahola that type safety itself is valuable in its own right without forcing the user to type little reminders to himself everywhere. Thanks to language servers, I can hover an expression in a text editor and remove all doubt.
I also agree with the other responses that if any language benefits from type deduction, it's C++. No way would the code be more readable if you were forced to be explicit about some of the dependent types in the STL.
That said, you are obviously not alone in your perspective. I've heard the exact same arguments from experienced C# programmers.
Type safety and compilation have never really mattered to me — it was always extremely easy to write safe programs in Python, without crazy indecipherable language grammars or long compile times. I would say having written and maintained large programs in C++ and Haskell, it is no easier to write safe programs in those languages than in Python. The compiler doesn’t save you time by catching bugs, that stuff is all just myth.
But what it does offer you is a way to communicate the design of your program through efficient type annotation, and give a lot of clarity into how things are intended to flow, and exactly at what points certain types of extensibility can be implemented.
I’m sure this can vary by project and personnel, but it has been really true for me. It is so, so easy to write safe, huge programs in Python, and the fear of hitting an uncaught runtime problem after lots of wasted time is misguided.
Meanwhile, the benefit of static typing in Haskell, for example, is that I can create stub functions for everything while working on the right type-level flow of operations.
Then I have a nice end to end skeleton code with expressive application-specific type descriptions as I start to fill in the implementation for the stubs.
And at the end, people can understand the code from reading the flow of type annotations.
Apart from those (admittedly) rare cases, after a few years using auto, I'm not as opposed as I was. Generally I use auto by default, and replace it with the actual type when I re-visit that code and have to actually think what the type would be. I'd guesstimate that I do that in, maybe 10% of the cases where I initially used auto. Makes code much more readable (as in, 'reading over'), too. Turns out it's only when you try to reason an algorithm through line by line that you actually need the type, and in the other cases (where you're just roughly following along, which I find happens more often than the other case) having 'auto' abstracts away some of the mental overhead of having type declarations.
Yes, but for other people reading your code, this would be way more often than 10% of the time.
So you save a tiny bit of effort in 90% of cases for you, while other people have to exert more effort in probably 90% of cases for them. It seems like the minute the number of people needing to read and understand that section of code exceeds 2 (you & one other), then this type of use of auto is actually increasing the amount of overall work required linearly for every additional person added in.
There is a group such as your self that value the extra context the type provides. I think the counter to is that modern tooling can provide this information to you. To split the difference you can use auto just where the type is redundant, like with make_shared, or verbose and unneeded, like with iterators.
Haskell and even Rust is less problematic in that area as Haskell does not have all those & const specifiers with complex rules of type deduction. And with Rust it is easy to see if a typeless let introduces a reference or copy or move.
how so ? most IDEs are able to tell you what type is behind your auto by a hover.
More often, the types don’t change all that much, but their behaviors get extended and new features have to be calculated in some block of code. If you can see the type explicitly, then you know what operations it supports, etc.
If I come across a structured binding where x and y are auto assigned as the unpacking of struct fields whose types might be complicated, now I have local variables x and y that I cannot reason about until I backtrack manually to figure out what type they will be deduced to having (and then keep that in memory any time I’m tinkering in that section of code).
I guess for the cases when big structural overhauls are happening behind the scenes to radically change underlying types and designs, auto would reduce a bunch of rework on type annotations. However, I just can’t believe anyone would allow that to be a common enough use case for it to matter more than explicit type annotations.
One is free to not use the auto keyword in a scenario like you mention in order to make the types explicit regardless of what the "Almost Always Auto" camp says.
However there are scenarios where leaving the type out does not degrade readability and sometimes improves readability. Often cited examples of situations where it may improve readability usually look somewhat like this:
void print_vector_of_maps(std::vector<std::map<std::string, std::string>> v)
{
for (const std::map<std::string, std::string>& item: v) {
for (const std::pair<std::string, std::string>& entry: item) {
std::cout << entry.first << ": " << entry.second << '\n';
}
std::cout << "---\n";
}
}
With the auto keyword, it looks like this: void print_vector_of_maps(std::vector<std::map<std::string, std::string>> v)
{
for (const auto& item: v) {
for (const auto& entry: item) {
std::cout << entry.first << ": " << entry.second << '\n';
}
std::cout << "---\n";
}
}
The types are still known from the surrounding context and the readability has arguably improved.I do, often enough (multiple times per month at least) that I have headers of typedefs for the alternative types that I have to use and which provide different performance characteristics and behaviours.
It's particularly useful with generic code that makes heavy use of templates, or code that uses iterators. In these cases, it just isn't that useful for the reader to know the exact type.
Then the usage of auto was expanded to help when writing generic code.
I think both of these cases are valid uses of auto, but people seem to have run away with it and will literally use it for statements like auto i = 0;
As a professional C++ coder, I personally don't have a problem with auto (or var in C# for that matter) but I'd prefer people use it where it's useful rather than for every little thing.
> modern C++ style using auto almost whenever possible.
Using auto everywhere, to me, is bad code. It's hard to understand what types we're dealing with, at a glance.
Types let the compiler reject a large set of invalid programs, which would otherwise produce a runtime error in a dynamic language.
for (auto foo : foos) {
foo.bar()
}
I don't care about the exact type of `foo`, so I let the compiler deduce it behind the scenes. However, I still want it to break my build if `bar()` doesn't exist!Who cares if the compiler can deduce it. That’s not helpful to me at all if I am scanning this section of code because I have to add more method calls inside the loop to calculate new results, and I don’t know what base type foo even is to get started with what would be required.
> “You assume that the point of using types is readability, which is false.”
This just seems wrong to me. Communicating your designed intention with type annotations is the number one reason to use them, whether you’re writing C++ or Haskell.
Getting the compiler’s help to prove correctness or avoid bugs is a secondary reason. Sometimes it becomes the primary reason in isolated cases. But usually it’s a secondary consideration nowhere near as important as using types to communicate the design of the program.
sure, but most haskell programs leave type annotations out, it's only some specific parts where it enhances clarity that it helps ; most of the time it would be unneeded noise, just like in C++.
I really don't want to go back to the dark days of
for(std::vector<std::pair<float, int>>::const_iterator it = v.cbegin(), end = v.cend(); it != end; ) {
if(it->second > 1 && std::distance(v.begin(), it) % rand() == 0)
it = v.erase(it);
else
++it;
}
versus for(auto it = v.cbegin(), end = v.cend(); it != end; ) {
if(it->second > 1 && std::distance(v.begin(), it) % rand() == 0)
it = v.erase(it);
else
++it;
}
In a lot of cases, it can even cause bugs : for instance, the iterator type of std::map<int, std::string> is std::pair<const int, std::string>.If you ever happened to write :
std::map<int, std::string> map;
// ...
const std::pair<int, std::string>& value = *map.begin();
then congrats, you have unneeded memory allocations because the pair will be copied in order to match the explicit type.whereas here :
const auto& value = *map.begin();
you know that you get exactly the correct type - maybe at some point you will replace with a boost::flat_map or another which has a different iterator type, and when you do this, you won't need to change any other code anywhere else - it will be automatically correct.