265
u/SamG101_
6d ago
•
Pooh needs about 50 more faces, for the 50 ways to initialise a variable in c++
https://leanpub.com/cppinitbook 300 odd pages
obligatory and thats just initialisation not assignment 💀
192
u/LRaccoon 6d ago
Default initialization:
int x;Copy initialization:
int x = 5;Direct initialization:
int x(5);List (brace) initialization:
int x{5};Copy-list initialization:
int x = {5};Value initialization:
int x{};orint x = int();Zero initialization:
static int x;Aggregate initialization:
Point p = {1, 2};Designated initialization (C++20):
Point p{.x = 1, .y = 2};Constant initialization:
constexpr int x = 10;Initialization with
auto:auto x = 5;Reference initialization:
int& r = x;Dynamic initialization with
new:int* p = new int(5);Smart pointer factories:
auto p = std::make_unique<int>(5);In-class member initializers:
int x = 5;inside a classConstructor member initializer list:
S() : x(1) {}Delegating constructors:
S() : S(5) {}Structured bindings:
auto [a, b] = pair;If/switch init-statements:
if (int x = f(); x > 0) {}Lambda init-capture:
[x = 5]() {}Copy/move construction:
std::string b = a;orstd::string b = std::move(a);Parenthesized aggregate initialization (C++20):
P p(1, 2);63
u/Blue_Moon_Lake 6d ago
I'm pretty sure some of these are useless and should be deprecated.
103
u/SuitableDragonfly 6d ago
Does anything in C++ ever actually get deprecated?
53
u/Blue_Moon_Lake 6d ago
Sadly no, which is why it's a mess to figure out what you should avoid doing and what you should do.
Which is dumb, because you can deprecate something without removing it.
22
u/arachnidGrip 6d ago
`-Wdeprecated`
-3
u/Blue_Moon_Lake 6d ago
What?
9
u/Str1dersGonnaStride 6d ago
Pass the flag to tell the build tools to warn you about things that have been deprecated
20
u/SuitableDragonfly 6d ago
If you never actually remove the thing you deprecated, there isn't much point to deprecating it.Â
21
u/Mateorabi 6d ago
To warn against using it because there’s a more modern idiomatic way of doing it.Â
18
5
17
u/arachnidGrip 6d ago
C++ has deprecated many things over the years but you need to tell it to warn you about deprecated features.
4
u/conundorum 5d ago
Yes, actually. Mainly library members, though, it's rare that a language feature will be deprecated because they don't want to risk breaking very important 20-year-old unmaintained libraries that the entirety of modern infrastructure depends on. (It's a meme, but we meme about it because it's true.)
The most notable one is dynamic exception lists (
throw(whatever)in the function signature), which got deprecated and mostly removed because nobody ever cared enough to actually support it. It was on life support for a while, where the "throws nothing" version (the only one that ended up beingnot worthless) is a synonym fornoexcept, and every other throw-list is dead, before it got the boot too in C++20 or so. And similarly, the most notable library feature is probably "good" oldstd::auto_ptr, which got deprecated in C++11 because it was kinda really bad andunique_ptrwas better, and finally got the boot in C++17.Apart from that... it's hard to find a good list online, really. There's a partial list here, but you'd probably have to scour the various standards to find something more complete.
Now, that said, being deprecated (or even removed) doesn't mean that compiler vendors actually listen, because they're the ones that have to actually support all those ancient legacy codebases. Especially if the compiler includes version switches. If a compiler includes, e.g., both
-std=c++11and-std=c++17, then it will never remove features that were removed in C++17; it can disable them for-std=c++17mode, but it still needs to be able to provide them for-std=c++11mode.So what it ultimately boils down to is that the language tries to deprecate & remove things, but legacy code is holding the compilers hostage.
3
u/AvidCoco 6d ago
Any good linter will warn about using dumb ones
4
u/Blue_Moon_Lake 6d ago
And how would someone inexperienced know if they're using a GOOD linter?
2
u/AvidCoco 6d ago
They’d google it?
2
u/Athropod101 5d ago
And they’ll find a bunch of linters, because C++’s toolchain ecosystem is amazing 😃
3
u/conundorum 5d ago
Eh... not really, weirdly enough. Some of them are just the same thing in different places and/or contexts (e.g., "copy initialisation", "constant initialisation", "initialisation with
auto", "in-class member initialisers" & "constructor member initialiser list", and "if/switch init-statements" are all the same feature in different contexts), and most of the others do different things under the hood (e.g., constructor delegation allows you to chain constructors, default initialisation lets you use the type's base rules, copy initialisation duplicates another object (or is optimised into direct optimisation if possible), direct initialisation hard-codes into the executable, zero initialisation sanitises memory, reference initialisation is singled out because it either registers a second name or creates a pointer, etc..).It's a case where the language makes it look more complex than it actually is... which, admittedly, happens a lot in C++. Most of these really just boil down to "how
Type t = val;works depends on whatTypeis", more than anything else.14
u/Big-Rub9545 6d ago
Besides one or two, almost all of these are doing entirely different things, or are entirely distinct syntaxes to begin with.
For example, these two are the exact same declaration:
- int x;
- static int x;The latter just declares a variable with internal linkage (assuming the value is at global scope). The rules related to initialization for such declarations are irrelevant since you’re still declaring the same thing. You can remove ‘static’ altogether.
It becomes very difficult to take many criticisms of the language seriously when it’s clear that most of the people making them seem to have never touched the language or tried to understand any of it.
2
u/nfitzen 6d ago edited 6d ago
Inside a function body, I assume
static int x;is like C and will declare storage with static lifetime; that is, it persists between function calls.Also, in the case of
int x;in function body scope, does C++ initializexto 0 by default? C certainly wouldn't (instead,xwould be uninitialized), but I don't really know C++.6
u/Big-Rub9545 6d ago
Yes for the first point.
For the second, it is also uninitialized in C++. This is the case for any primitive type (compound/composite/custom types can be default- or zero-initialized through implicit constructor calls with the same syntax).
You can just zero-initialize the variable by appending a pair of braces, which I do with every variable I don’t care to explicitly initialize:
int x{};4
u/conundorum 5d ago
There are a few contexts where
xwould be zero-initialised (mainly related to classes (structs with their helper functions built into them so they don't pollute the global namespace), IIRC), but it's usually the same as C.On that note, though, one of the things C++26 will change once it's officialised (or has changed, if it already is) is that reading uninitialised variables is now an error instead of UB, to prevent compilers from ignoring pre-assignment reads. Creation still works fine, it's just reading that gets changed. (And you can keep the old behaviour by declaring the variable
[[uninitialized]], if needed/desired.)1
u/SamG101_ 6d ago
Don't forget some initialisation changes depending on the availability of a template arguments initialisation-ness
1
u/No-Finance7526 6d ago
Dynamic initialization with
new:int* p = new int(5);
Smart pointer factories:auto p = std::make_unique<int>(5);Isn't that just assigning a value?
-1
1
u/headedbranch225 3d ago
What is the difference between copy and direct? And also the others that look similar
1
u/chaudhary-theodore9 2d ago
`T x = value;` is copy-init, so it cannot select an `explicit` converting constructor; `T x(value);` is direct-init and can.
1
u/ACoderGirl 6d ago
I'm really glad to work with Go these days. Is it a perfect language? Far from it. But it's such a relatively straightforward and unsurprising language. Very readable and predictable. Makes it easy to work with.
I still do appreciate more complex languages for the beautiful abstractions you can make, but especially as I read code more than I write it (and even more so with AI), Go's readability makes it perfect.
240
u/Ai--Ya 6d ago
static constexpr auto a{10};
102
83
u/GoodiesHQ 6d ago
I love how you can just do
auto auto = auto
And it just infers the rest from context
22
u/RajjSinghh 6d ago
In what context would this even work?
0
u/Mippen123 4d ago
My assumption is this would work if you have a variable named auto and declare a variable shadowing that variable (i.e. also called auto) in the current scope (letting it deduce the type to the same type as the first auto-variable).
2
u/K722003 3d ago
You cant do this, cuz
autois a keyword. You'll probably run into a unqualified id error when trying to compile it. C++ doesn't let you make keywords into variables. The closest way to "shadow" a keyword is by using a define macro, for example something we do in like codeforces is to#define int int64_t(and dosigned main()instead) so that we just don't have to worry about integer overflow issues.13
4
-24
u/MouseNcactus 6d ago
What a rusted way to do C++.
1
u/AvidCoco 6d ago
The correct way to do C++
1
u/Qwertycube10 6d ago
I think auto here is awful, you should actually choose an integer type instead of relying on the type deduced by the initializer (pick signed or unsigned and pick a size for your ints.)
3
u/AvidCoco 6d ago
No you should use auto with literals like 10UL, 10UZ etc.
1
u/Qwertycube10 6d ago
I much prefer to use the type if it is not super long
2
u/AvidCoco 5d ago
The idea is that the type should come from the value not the assignee otherwise you might get implicit conversions.
With ints it doesn’t actually matter but it’s a good habit to get into.
125
42
u/East-Law-2877 6d ago
auto a = int{10};
17
u/CortlandNation9 6d ago
I won't allow it
4
u/Zenkibou 6d ago
It's consistent with other modern initializations, though. Like "auto sp1 = std::make_shared<C>(1);"
1
u/conundorum 5d ago
As written, yeah. It can come up with templates, though. Usually when working with dependent types, and/or a function returns an awkward-to-create type.
2
7
30
19
u/tiajuanat 6d ago
Everyone calls Rust syntax ugly, but I'm constantly reminded that C++ is infinitely worse
13
u/Wertbon1789 6d ago
Rust is readable, if you know that most stuff is an expression. Then you see C++ where move-semantics and any type of cast is syntactically a generic function that does some magic shit, because they didn't have enough special characters left to use.
11
u/Maleficent_Memory831 6d ago
I used to do a lot of C++. I taught it at university with Cfront, the first compiler for it. In my career I was often the team's expert in it. Over time I got a bit annoyed at it's changes. Then more recent surprised at such silliness going on in the standards.
So a couple design flaws crop up now and then. First, the the need to twist and abuse syntactic elements. Second, the inability to say no to adding all available options (public/private is good, but then also protected, and then friends, and then const is good, but also mutable).
I was on a more recent team (I'm mostly on C these days) where guys writing a C++ side of things seemed more intent upon proving how clever they were with their code rather than applying the K.I.S.S. principle, more intent ona changing APIs in the middle of a release cycle than in helping get the project out on time.
4
u/Qwertycube10 6d ago
Those all solve real problems and not having them would force worse design. (Except protected, I strongly believe that using it means your design was very likely poor). They can be misused, but better that than have awkward holes in the language.
3
u/conundorum 5d ago
protectedis mainly meant for cases where you want to provide functions that only child classes can use. It's essentially a limited form offriendship, where instead of blindly declaring all subclasses friends somehow, you can just protect a single getter/setter pair or whatever....It's rare that this is useful, though, for sure. I think the intent is just to help with code injection in certain very specific cases, so that you can use a child class to modify the base's behaviour in a way that's not externally visible? That, and as a way to guarantee polymorphic destruction for interfaces (and prevent accidental slicing in certain corner cases), by making it so that the base class' destructor can only be called by subclass destructors. Either way, it feels like it's mainly meant for use in interfaces & other abstract classes.
That said, it is very easy to misuse it, especially when you're new to the language.
1
u/mutexsprinkles 4d ago
Yeah, protected data members are where it really gets a bit smelly.
If you're providing an invariant to your inheritors, don't let them randomly fuck with the state.
7
u/MouseNcactus 6d ago
Isn't "proving cleverness over KISS" sickness of entire industry?
2
u/edgmnt_net 5d ago
In some ways, but not clearly. There's a whole parallel debate between overengineering and plain bad engineering. I would say I rarely see stuff that really qualifies as "too clever". It's more often along the lines of a combination of ignorance (you don't know how this is supposed to be done), scope creep (this seems nice to have, but you'll just half-bake it) and trivial layering (this could've been 10 lines of code, but now it's 5 whole files and you've not even made any attempt at an actual abstraction).
3
4
u/That-Cpp-Girl 6d ago
I would hope no one does this, but `int a{};` instead of `int a = 0;` might make sense.
4
u/Scarcity-Nervous 6d ago
Only because of implicit in-place construction of native types, but technically correct. Well played 🫡
5
2
12
u/Lawn_Meower_ 6d ago
13
u/-Ambriae- 6d ago
Damn gurl why on earth did you get downvoted? God forbid someone happens to like unconventional syntax ðŸ˜
2
8
4
u/patrlim1 6d ago
This is why I use C
3
u/the_SCP_gamer 6d ago
int a = (int){10};5
1
u/conundorum 5d ago
CTHULHU a = FHTAGN 10;
Where#define CTHULHU intand#define FHTAGN (int), just to make it more alien.
3
3
u/ElKuhnTucker 6d ago
Once you debug somebody else's "witty" code, you really appreciate code that looks like it was written by a 5 year old
2
0
u/Raid-Z3r0 6d ago
If you open a PR with that syntax for me to review, I'm not even bother requesting changes. That shit is straight up rejected
6
u/Big-Rub9545 6d ago
For what reason? This is well-known syntax to any frequent user of the language. It’s even the syntax recommended by Bjarne himself.
4
u/conundorum 5d ago
Different people like different distinctions, basically. To some people, this nicely differentiates between initialisation & assignment. But to others, it's an abomination that lies about being a compound object (aggregate/list/array/etc.) when it really, really isn't.
Especially since
int a = {10};is also a thing, and has a different meaning than either of those.2
u/Big-Rub9545 5d ago
These are often just forced aesthetic views with no proper backing. Another way to instead look at braces is initialization syntax sugar, where the values enclosed in braces are processed in total to construct an object. For compound types, those values would be field values; for arrays, element values; for primitive values, their direct initializers.
Everyone can keep their own style preferences but most of these hard lines are just people (who often don’t like the language to begin with) making weird dictates with vague reasoning.
1
u/Original-Ad-8737 5d ago
that syntax is an abomination.... curly brackets are for lists and having them everywhere makes code less readable
3
u/Big-Rub9545 5d ago
You use curly brackets in every block in your code. If those don’t make it any more difficult to read, then this shouldn’t, either. Using curly brackets for lists is likely one of the rarer use cases for them across a codebase (not to mention that this is entirely a language-specific designation).
1





29
u/LB-- 6d ago
It's great because 1. it disables implicit narrowing conversions and 2. initialization and reassignment look visually distinct at a glance. I never initialize with = anymore so any time I see = I know it is changing an existing value.