77 points · by nayuki · 7y ago · 57 comments
> int foo(void)/int foo()
In c, int foo() means that foo takes any number of args; c++ rightfully realised that that was stupid and removed that feature, which means int foo() can now be used to mean foo takes no args. Also, int foo(void) is illegal in c++.
Varargs in c are a complete pita to use, not to mention they literally do something different from function overloading/default args.
Constexpr is much nicer and safer to use than a macro.
Using malloc and calloc to make class instances means you can have unconstructed objects, which is a Bad Thing, and while introducing a new operator to do that is not necessarily the best way to handle that, it's a perfectly valid way of doing so.
Libc random is just garbage, and libc++ random is actually decent.
setjmp/longjmp are more complicated to use than try/catch, and don't have all the same functionality.
<iostream> functions are type aware (although really they should have used fmt).
I'm no c++ apologist (it's an awful language), but this listicle is just...not great.
"Don’t automatically assume that C++’s situation is desirable, necessary, or inevitable."
It seems to be trying to frame this as C++ having bad duplication. But many of the things listed are not actually strict duplicates at all - like pointers vs. references, since references cannot be null (yeah yeah you can force it but 'int& foo = nullptr;' doesn't compile, either). Which if you then read the explanations at the bottom tend to cover in a fairly non-biased way.
Yes, that's probably why the article's title is "Near-duplicate features of C++".
> references cannot be null
From the discussion and examples, that seems to be a restriction on the programmer, not a feature of the feature.
Being a restriction and being a feature are not mutually exclusive. Strong typing is a restriction on what's a collection of bits. Functions are just restrictions on your ability to change the PC. Loops are just restrictions on your ability to jump.
Restrictions are necessary to create structure.
void test() {
int* p = 0;
int& r = *p;
}
compiles without complaint.But if you do
int& r = *((int*)0);
You'll find it will warn, and tell you that what you're doing is illegal:<source>:2:14: warning: binding dereferenced null pointer to reference has undefined behavior [-Wnull-dereference]
Same if you try to naively return nullptr on a method that returns a reference:
int& iref() {
return nullptr;
}
<source>: In function 'int& iref()':<source>:6:12: error: invalid initialization of non-const reference of type 'int&' from an rvalue of type 'std::nullptr_t'
6 | return nullptr;
| ^~~~~~~
Compiler returned: 1If you get a null reference, this is by chance and not by design.
As you've shown, references can be null, but theyre not supposed to be and are assumed nearly universally to not be.
The argument comes down to when the undefined behavior occurs: is it at the deference to create the reference, or is it on the first memory access using the reference? The language pedants will say the former, but in practice, it's the latter.
In practice, you'll likely be able to invoke a member function on a null pointer or reference, as long as that member doesn't directly or indirectly access data members, or virtual functions of the type. Obligatory, I dont recommend doing this or relying upon this behavior, it's just behavior I've seen in my 2 decades of debugging C++.
Uh, citation needed. It would make compatibility with C libraries harder for no good reason. I believe it is valid as both declaration and definition.
Both g++ and clang++ accept it without even a warning.
foo(void) seems less likely to cause confusion to anyone who hasn't got that C vs C++ distinction uppermost in their mind - I didn't. Nobody knows C++, we all know a subset of it and a smaller subset than we think we do and actually use, despite pretty constant study! Anything you do that makes a reader less likely to be confused, to make it less likely that they will or should break their flow by looking up the rule, is a good thing (tm).
C++ suffers from "macho coding" styles and ethos quite badly. "I /believe/ I understand this subtlety at this moment so anyone who doesn't is stupid." Even when we didn't understand it ourselves just last week we forget it(!) We fool ourselves into thinking anyone who hasn't got at least a decade of hacking C++ every day is unworthy of reading our code, possibly pretending that 6 months can attain that level of oneness with changing standards.
I try to use popular and safer features without thinking about it and if I want to use something slightly less popular when there is a choice, I ask "what problem am I solving? Is lowering readability a price I'm happy to pay here?" Before charging ahead with it. I probably classify some of the latter as the former due to over-familiarity.
The ideal C++ code is rapidly readable and understandable without extremely taxing effort by a smart highschool student with 2-3 months of C++ experience. (Note the use of the word ideal in that sentence). s/C++/any language/ is also applicable.
Other than following the style of the project you're working on is there any reason to use a reference ever over say a const pointer? Or a const pointer to a const object? The syntax then makes it clear you're not dealing with a pass-by-value copy. Maybe in another world everything would be const by default and have to be marked mutable then references might go away - but C++ couldn't do that and compile C which explains /some/ of the tension inside the language between various C++ features. Shame they didn't make references const by default if they had to introduce them. And member functions defaulting to const and explicit constructors by default. Const construction by default etc. There was an opportunity lost a long time ago to tighten up everything that isn't legal C as far as possible with the programmer having the option with an additional keyword.
What makes you think that?
I'm looking at C++ 17, 11.3.5 (4).
> A parameter list consisting of a single unnamed parameter of non-dependent type void is equivalent to an empty parameter list.
What are you looking at?
I disagree. It does not include a contemporary RNG, and seeding the only decent one correctly is ridiculously difficult.
Objective-C has the same issue, for the same reasons.
Author has a point there, but maybe, just maybe, we won't see "new"s or "delete"s in most future codebases? (we have smart pointers now) Or non-intuitive macros (yay constexprs!)
I see these as stepping stones from C to where we are today without breaking everything at once or doing it with a whole other programming language.
I haven't seen 'new' or 'delete' in the wild for a decade now. (Well, except for various legacy libraries or student code on Github.)
And then you have the fun of passing those to a function. Do you pass by value (shared_ptr) or by reference (I believe you do not) or pass a naked pointer (when you need to pass a unique_ptr to a function that uses, but does not modify or cache the pointer, if I remember correctly). And then suppose you want to give away your unique_ptr, that's fun.
And if you want to deallocate your shared_ptr that's part of a cycle, you'll need to either use a weak pointer or manually reset it.
Apples and oranges. Smart pointers are wrappers over raw pointers. They extend functionality, but are not the same.
> Except that you generally create them with std::make_shared() and std::make_unique()
Again, apples and oranges. You're confusing factory functions that wrap memory allocation for convenience with actual memory allocation.
At most you could only complain that those factory methods duplicate the role of constructors, which would be silly.
> And then you have the fun of passing those to a function. Do you pass by value (shared_ptr) or by reference (I believe you do not) or pass a naked pointer (when you need to pass a unique_ptr to a function that uses, but does not modify or cache the pointer, if I remember correctly).
There is no duplication in your examples. You are just unaware of how those functionalities are used.
And comparing a function pointer to a lambda expression is quite laughable.
Also, this should be viewed as C++ features C doesn't have: It's 2019 C, shouldn't be accepted anymore
On the other hand, I still prefer C to C++ mainly due to the compile time (an incremental compile in a typical large C project I deal with takes a second or so, while C++ takes 3-4 seconds). C++ doesn't have to be slow, as long as you use the needed features. But idiomatic C++ means you'd be using STL, class inheritance, virtuals, operator overloading, templates and constexpr and stuff, all of which contribute to longer compile times.
The obvious solution is to avoid C++ when making new codebase, but that's easier said than done.
Of course there are duplicate features, that's an obvious downside to keeping backward compatibility while still allowing improvement.
If two equivalent/overlapping features were introduced in the same C++ version, then, yes it would be an indicator of a faulty design process.
• I feel that many commenters missed the fact that I was writing about NEAR-duplicate features of C++; I never said they were identical. But these features overlap so much that often all the alternatives are applicable in a real-world situation, and the choice becomes somewhat arbitrary, and you tend to see divergence between different coders and over the years.
• I'm surprised to see that no one said anything like "Indeed, I do see these near-duplicate features in the C++ codebase that I work with. And it bothers me because I had to learn two things instead of one, and we have no stylistic consistency".
• Some people expressed doubts about why I wrote the article. My intent and tone are clearly exhibited in the opening three paragraphs of the article; please reread them fully before judging.
• Many people dwelled on the difference between references and pointers. I firmly support references and use them in my published code. But I've seen many people who learn C++ after C, and they try to use C-style pointers for as long as possible to avoid learning the new, native C++ feature which is much safer. Hence you cannot avoid seeing pointers in C++ if you read/edit code that come from diverse sources.
• Many of my bullet points received no comments. I take it that either no one cares, or no one recognizes these points. For example, is it really sane for a language to have 3 ways of initializing a variable? (int i = 0; int j(1); int k{2};)
• A subtread about const-by-default is something I agree with, though the syntax would mismatch semantics in C. Regardless, Rust is a relatively new language with nearly all of C++'s powerful features, and indeed it implements immutable-by-default.
• I used new/delete in C++ in my early days, as a naive coder coming from C and Java with their manual management of memory allocation. But now I avoid those and rely on std::vector, std::unique_ptr, and RAII, which are safer and more concise.
• (Previous thread: https://www.reddit.com/r/cpp/comments/6clwkq/nearduplicate_f... )