7

cppreference shows the following definition of std::in_place_t:

struct in_place_t {
    explicit in_place_t() = default;
};
inline constexpr std::in_place_t in_place{};

Why have they added an explicit and defaulted constructor? Why it isn't left out? What are the benefits?

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Martin Fehrs
  • 792
  • 4
  • 13

2 Answers2

4

If you leave out the constructor it will not be explicit. If you don't = default it it will not be trivial.

So, if you want the constructor to be explicit and you also want it to remain trivial, what you see is the only option available.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • @davidbak Thank you. – Jesper Juhl Mar 18 '19 at 16:04
  • 6
    It would be good to know why it's important to have the constructor explicit and trivial in this case. – Martin Fehrs Mar 18 '19 at 16:07
  • 2
    I was expecting answer like: "without `explicit` this kind of code `...` will compile and we don't what that since ... ". Current version can be rephrased to: "it is like it is", so I don't get it why it so highly voted. I think everyone understand what `explicit` and `default` do here, question was: why? – Marek R Mar 18 '19 at 16:25
4

You want a type like this to only be explicitly constructible, because it exists to denote a particular kind of constructor overload, in places where {} might reasonably be found.

Consider the following constructions

std::optional<DefaultConstructible> dc1({}); // dc1 == std::nullopt
std::optional<DefaultConstructible> dc2(std::in_place); // dc2 == DefaultConstructible()
Caleth
  • 52,200
  • 2
  • 44
  • 75
  • It would be worth mentioned the technique being used in the constructor (or in more general method) overload is tag dispatching. – Niall Mar 18 '19 at 18:10