10

In this presentation: http://qtconference.kdab.com/sites/default/files/slides/mutz-dd-speed-up-your-qt-5-programs-using-c++11.pdf

The author suggests that N-ary constructors benefit from the C++11 version of explicit keyword.

What changed in C++11 that makes this keyword useful if you have more than one constructor parameter?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
Klaim
  • 67,274
  • 36
  • 133
  • 188

1 Answers1

16

In C++11, if you have a non-explicit constructor for a class A that has multiple parameters (here I use A::A(std::string, int, std::string) as an example), you can initialize an argument of that type with brace initialization:

void foo(A a);
foo({"the", 3, "parameters"});

Similarly, you can do the same with return values:

A bar() {
  return {"the", 3, "parameters"};
}

If the constructor is, however, explicit, these will not compile. Hence, the explicit keyword now has importance for all constructors, rather than just conversion constructors.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • Could you give an example where it is useful to forbid brace initialization? What harm could brace initialization do? – Ali Dec 15 '12 at 08:40
  • 1
    @Ali Someone on the new standard C++ committee public forums pointed to this question that should more or less answer yours: http://stackoverflow.com/questions/9157041/what-could-go-wrong-if-copy-list-initialization-allowed-explicit-constructors – Klaim Dec 15 '12 at 14:13