0

If myClass is a class, what's the difference between defining obj as myClass obj(var1, var2) and defining it as myClass obj = myClass(var1, var2)?

Invariance
  • 1,027
  • 1
  • 7
  • 15
  • In C++11 or later: a usually-elided move. In C++98, it was a usually-elided *copy*, which caused problems since moves didn't exist yet. – o11c May 12 '18 at 21:21
  • 3
    @o11c: Why did it cause problems if it was usually elided? – Kerrek SB May 12 '18 at 21:22
  • Certainly a valid question. I suspect there's a duplicate somewhere. – Drew Dormann May 12 '18 at 21:23
  • @KerrekSB Because the copy-ctor had to *exist*, even if it ended up not being called. Move-only types are very convenient. – o11c May 12 '18 at 21:23
  • @o11c There were no move-only types in C++98, so no problem. – juanchopanza May 12 '18 at 21:24
  • @juanchopanza Incorrect, there was simply no *language* support for them. The library-level implementation does not work in this case, which is the problem. – o11c May 12 '18 at 21:25
  • 1
    @o11c That really makes no sense. – juanchopanza May 12 '18 at 21:25
  • @juanchopanza the `.swap(T&)` member functions were the most common library-level move implementations, but it's also possible to use e.g. a template class. – o11c May 12 '18 at 21:27
  • 2
    In C++17, I believe there's no difference between these, barring any most vexing parse differences you might run into more generally. – chris May 12 '18 at 21:32
  • 1
    I feel that the "duplicate" is too broad; in general there are a lot of differences between copy initialization and direct initialization; but not for OP's specific case (initialization from expression of the same type). – M.M May 13 '18 at 01:14

0 Answers0