Initialization variable (pointer and value)

Foo f1 = Foo(); // (1) Ok Foo f2 = Foo; // (2) Compiler error Foo *p1 = new Foo(); // (3) Ok Foo *p2 = new Foo; // (4) Ok. Why?? 

I was wondering why there are two ways to initialize pointers. It looks a bit inconsistent. Is there any logical reason, and if so, what? Or maybe it's some kind of legacy? And if so, what is the origin of such designations?

+4
source share
3 answers

It's a little ... complicated, to say the least.

When working with objects, both notations are equivalent. When using primitive types (for example, int ) (3) will initialize (zero filling) the value, but (4) will not (the value will remain undefined).

For automatically assigned objects, this is:

 Foo f1; 

Declares and initializes the Foo object using the default constructor. It:

 Foo f2 = Foo(); 

Declares and initializes the Foo object using the copy constructor, essentially copying the value of the temporary object ( Foo() ), which is built using the default constructor.

+4
source

I give you that this seems illogical, but if you think about the possible meanings, it makes a lot of sense.

Not knowing what Foo might be, neither the person nor the compiler (the human perspective is more important here) could determine if Foo f2 = Foo; a) creating a new temporary object Foo and copy building another one with it; or b) assigning the value of the variable Foo instance built for copying ( f2 ). This may seem obvious to us, because our convention tells us that Foo should be a type, since it is capitalized, but in general it is not so simple (again: this mainly refers to the human reader, who does not necessarily have the entire source code is remembered )

The difference between (2) and (4) is that only one interpretation is allowed for the latter, because new var (where var is a variable) is not a legal expression.

+1
source

Equivalent 4 for area based resources is actually just

 Foo f; 

The inherited reason for the differences is that in C primitive types, such as int , were not initialized by default with something useful. C ++ inherited this behavior for performance reasons - at that time. Of course, now this is a trivial amount of processor time to spend. In C ++, they introduced a new syntax with which it will always be initialized - brackets.

 int i = int(); 

i always guaranteed to be 0.

 int i; 

The value of i is undefined.

This is the same as for a pointer sort, only with some new :

 int* i = new int(); // guaranteed 0 int* i = new int; // undefined 
+1
source

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


All Articles