C++ Logo


Advanced search

Re: Constructor ambiguity: Uniform initialization vs. initializer lists

From: Arthur O'Dwyer <arthur.j.odwyer_at_[hidden]>
Date: Tue, 5 Oct 2021 08:57:23 -0400
On Tue, Oct 5, 2021 at 8:12 AM Gawain Bolton via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> I would like to report what I will call "constructor ambiguity" for
> classes which have multiple constructors, one of which have takes an
> initializer list.
> The ambiguity is for us humans, not the compiler, and is due to the two
> things:
> 1. The same syntax is used for uniform initialization and initializer
> lists.
> 2. Any constructor taking an initializer list is preferred when braces
> are used.
Yes, this is well-known. See for example
>From the end of that blog post:

Simple guidelines for variable initialization in C++:


   Use = whenever you can.

   initializer-list syntax {} only for element initializers (of containers
   and aggregates).

   function-call syntax () to call a constructor, viewed as an

In your examples, that would be
  std::string sa = std::string(32, 'A');
  std::string sb = {32, 'A'};
  std::vector<int> va = std::vector<int>(10, -1);
  std::vector<int> vb = {10, -1};

Of course `sa` and `va` could use `auto`; and in practice that's what I'd
do, personally.


Received on 2021-10-05 07:57:39