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); 
6
  • 3
    In this context they are identical, and the first one is preferred. Commented Oct 22, 2018 at 20:34
  • Why is the first one preferred? Commented Oct 22, 2018 at 20:35
  • Because there is no pointless repetition. Commented Oct 22, 2018 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 Commented Oct 22, 2018 at 20:36
  • 1
    One difference is that the second form requires a copy constructor pre-C++17. See stackoverflow.com/questions/1051379/…. Commented Oct 22, 2018 at 20:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
The copy was most likely elided pre-C++17, and in C++17 it is guaranteed to be elided.
It's not "epsilon"
@juanchopanza in C++17 there is not even a copy to elide, these two syntaxes both specify a variable constructed from argument 10

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.