C++ Logo

STD-PROPOSALS

Advanced search

Subject: Re: [std-proposals] Fixing some initialization gotchas
From: Eyal Rozenberg (eyalroz_at_[hidden])
Date: 2019-08-23 16:57:52


IMHO, what you're describing is a specific problem with std::vector (and
possible with a few other standard library containers) rather than with
the language. `std::vector` most definitely has too many constructors -
more than it should, enough to make constructing vectors confusing
together with the default parameters (especially vectors of integers).

Personally, I try to avoid constructors 3 and 4 in the listing here [1],
i.e. "never initialize a vector with a single integral number" (in favor
of default-initializing and reserving).

Having said that - I don't see how tinkering with
initialization-vs-assignment would be much help at this point in time.
C++ will still be kind of broken w.r.t. initialization, just in a
different way.

Eyal

[1] : https://en.cppreference.com/w/cpp/container/vector/vector

On 24/08/2019 0:00, Hyman Rosen via Std-Proposals wrote:
> I am not in favor of the status quo.  I believe that C++ is broken,
> probably beyond redemption, and I'm dubious that band-aid fixes
> here and there are going to make things better.
>
> You say when you look at `auto x = {1}`, the only logical explanation in
> your mind is that the RHS is an initializer list but you have no intuition
> for `auto x{1}`.  But in the context of teaching C++, why would that be?
> What is it about the presence or absence of the `=` that will speak to
> the intuition of the student?  Are students supposed to know about
> initializer lists at all?  Aren't they supposed to be behind-the scenes
> magic that let you write intuitive initializers without thinking about how
> they work?
>
> Also, even without `auto` things are unteachably strange.
>
> `vector<int>vi3{3};` gives me a vector containing a single 3.
> `vector<string>vs3{3};` gives me a vector containing 3 empty strings.
> `vector<int>vi0{0};` gives me a vector containing a single 0.
> `vector<string>vs0{0};` has undefined behavior and usually crashes.
>
> If I use `=` before the braces, the only thing that changes is that the
> `vs3` line doesn't compile, with messages about vector's constructor
> being explicit.
>


STD-PROPOSALS list run by herb.sutter at gmail.com

Standard Proposals Archives on Google Groups