jeudi 19 mars 2020

Initializing Variable Allocated with New Operator in C++

When I was got into Dynamic Memory in C++, I realized it has some weird syntax and I am confused about the difference between:

int* ptr1 = new int(5);

and,

int* ptr1 = new int{5};

and why the first one can't be used with arrays like,

int* ptr2 = new int[3](1, 2, 3);

and {} is used instead of (). Are there reasons behind the syntax differences and are there other differences other than just syntax?

In the first case why can't we use just = to initialize?

One more thing is, there are new and new[] operators I suppose but, we don't use [] next to new keyword, but next to type_name, am I understanding this incorrect or if I've written that as int* ptr2 = new[3] int{1, 2, 3}; it would be still correct?

Aucun commentaire:

Enregistrer un commentaire