C ++ Create an object from a class in two different ways

I am almost sure that this was asked earlier, but I can’t find it for life through search.

So here it is:

What's the difference between:

MyObj myObj; 

and

 MyObj myObj = MyObj(); 

I believe that both achieve the same result, but is it better to use than the others? Suppose all I want is the default constructor.

* edit - I heard that the first is more suitable, since the second first creates the object through the default constructor, and then assigns myObj. The first “assign” operation is missing, so the first will be “faster”. True?

+8
c ++ object instantiation constructor
source share
3 answers

Yes, there may be a difference.

In the first case, myObj not initialized if it is a POD type, otherwise it is initialized by default.

The second instance of myObj initializes the copy from the initialized value. A temporary possibility (and almost certainly should) be eliminated in order to initialize the effect value.

If myObj has a constructor, then the constructor will always be called. For the first case, the default constructor should be available, for the second, both copy and default constructors should be available, although only the default constructor can be called.

In addition to the obvious difference between “uninitialized” and initialized values ​​for POD types, there is a difference between default initialization and value initialization for non-POD types without user-defined constructors. For these types, POD members are not initialized with default initialization, but are initialized with the zero initialization value of the parent class.

+9
source share

The first is the announcement, the last is initialization.

If MyObj is not a POD, then there is no difference except that the copy constructor must exist and be available in the latter case (although it was not called).

If MyObj is a POD, then the first does not initialize it, the contents of the MyObj variables will be unspecified. The latter is the only way to "zero" initialize a non-aggregate POD.

+4
source share

Without many explanations. The first uses the default constructor to initialize myObj. The second actually creates a temporary instance, and then uses the copy constructor to initialize myObj. (remember that a default copy constructor is also created, not just the default constructor)

0
source share

Source: https://habr.com/ru/post/650362/


All Articles