C++ Logo

std-proposals

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
https://quuxplusone.github.io/blog/2019/02/18/knightmare-of-initialization/
>From the end of that blog post:

Simple guidelines for variable initialization in C++:

   -


   <https://quuxplusone.github.io/blog/2019/02/18/knightmare-of-initialization/#use-whenever-you-can.>
   Use = whenever you can.
   -


   <https://quuxplusone.github.io/blog/2019/02/18/knightmare-of-initialization/#use-initializer-list-syntax-only>Use
   initializer-list syntax {} only for element initializers (of containers
   and aggregates).
   -


   <https://quuxplusone.github.io/blog/2019/02/18/knightmare-of-initialization/#use-function-call-syntax-to-call>Use
   function-call syntax () to call a constructor, viewed as an
   object-factory
   <https://quuxplusone.github.io/blog/2018/06/21/factory-vs-conversion/>.

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.

HTH,
Arthur

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