0

There are multiple ways of initializing an object in c++. There are two examples below, ent1 and ent2. I'm wondering what the difference is, and is one of them more 'correct' or preferred over another?

class Entity {
public:
    int h;
    Entity(int health) : h(health) { }
}

Entity ent1(10);

Entity ent2 = Entity(10);
joey
  • 19
  • 1
  • 3
    In this context they are identical, and the first one is preferred. – paddy Oct 22 '18 at 20:34
  • Why is the first one preferred? – joey Oct 22 '18 at 20:35
  • Because there is no pointless repetition. – paddy Oct 22 '18 at 20:35
  • 2
    Makes sence. You say 'in this context they are identical'. In what context will they NOT be identical? Because it's weird that there are 2 ways of making an object if they are identical – joey Oct 22 '18 at 20:36
  • 1
    One difference is that the second form requires a copy constructor pre-C++17. See https://stackoverflow.com/questions/1051379/is-there-a-difference-between-copy-initialization-and-direct-initialization. – juanchopanza Oct 22 '18 at 20:38
  • Some people prefer `auto ent3 = Entity(10);` – M.M Oct 22 '18 at 21:58

1 Answers1

2

In C++17, both of these are identical. Pre C++17, however, there is a subtle difference as follows:

The one below is a copy constructor. This will create an anonymous Entity and then copy over to ent2, although the copy may be omitted subject to copy epsilon.

Entity ent2 = Entity(10);

The one below is a direct instantiation, the memory for ent1 will be allocated and value 10 will be placed in the area specified by the constructor.

Entity ent1(10); 

The reason direct is preferred, in pre C++17, is because it doesn't require the extra copy step. This advantage is non-existent in C++17.

Kon
  • 4,023
  • 4
  • 24
  • 38
  • I am pretty sure the standard says the first one is _not_ copied. It _looks_ like it would be, but it is in fact treated exactly the same as the second. – paddy Oct 22 '18 at 20:39
  • 4
    The copy was most likely elided pre-C++17, and in C++17 it is guaranteed to be elided. – juanchopanza Oct 22 '18 at 20:39
  • It's not "epsilon" – M.M Oct 22 '18 at 21:59
  • 1
    @juanchopanza in C++17 there is not even a copy to elide, these two syntaxes both specify a variable constructed from argument `10` – M.M Oct 22 '18 at 21:59