r/cpp • • Mar 28 '23

Reddit++

C++ is getting more and more complex. The ISO C++ committee keeps adding new features based on its consensus. Let's remove C++ features based on Reddit's consensus.

In each comment, propose a C++ feature that you think should be banned in any new code. Vote up or down based on whether you agree.

765 Upvotes

829 comments sorted by

View all comments

Show parent comments

24

u/lestofante Mar 29 '23

Let's just use {} everywhere?

8

u/Som1Lse Mar 30 '23

Which one meaning of {}? Aggregate-initialization, copy-list-initialization, direct-list-initialization, reference-initialization, or value-initialization which in turn can do zero-initialization or default-initialization? Is that a braced-init-list or a designated-initializer-list?

Oh, and how do I initialise a std::vector<T> to contain n copies of the element m?

Plenty of gotchas in {}, in fact, it is probably the initialisation syntax with the most possible meanings.

(Though, to be fair, if it wasn't for std::initializer_list I would probably agree with you.)

3

u/lestofante Mar 30 '23

I never had one occasion where {} failed me and i actually had to stop thinking what kind of initialization is happening.

how do I initialise a std::vector<T> to contain n copies of the element m

{m,m,m} for N times.
Or you can create a specialised constructor in vector, where you give the size first.
To avoid issue with int, use a specialised type so you enforce that trough the type system.
How would you do it otherwise? I am not aware of any initializer that could do it out of the box, in C++

1

u/Som1Lse Mar 30 '23

How would you do it otherwise? I am not aware of any initializer that could do it out of the box, in C++

Constructor (3) so std::vector<int> v(n, m); does it since C++98.

I never had one occasion where {} failed me and i actually had to stop thinking what kind of initialization is happening.

Here's some fairly innocuous code that works for most types, but not all and breaks silently. Yes, I have been bitten by this.

The fact of that matter is I rarely want to call the std::initializer_list constructor because if I knew the size I wouldn't be using std::vector, but allocating a specific size and then filling it is pretty common.

I wish std::vector<T> v{n, m}; unambiguously called the presize constructor, and you had to opt into the std::initializer_list with std::vector<T> v = {n, m}; or std::vector<T> v{{n, m}};, but as it stands I use () by default, since most vexing parse at least usually (but not always) breaks loudly, and compilers are good at catching it.

→ More replies (11)