Note that I'm learning on Visual C++.
As I know, we should zero a dynamic array this way:
void main()
{
int *arr = new int[15];
memset(arr,0,15*sizeof(*arr));
...
delete [] arr;
}
But I found another way to do the same:
void main()
{
int *a = new int[15]();
...
delete [] arr;
}
As you can see, I just added two parentheses after the brackets. But it works only if I set the size of the array.
I can't find any information on this, and I don't know what purposes this is needed for.
EDIT: First code is edited and verified by VC compiler now. EDIT2: So I can't find manual about 2nd code on MSDN. There I can find this one? (No Google plz)
I can't find any information on this, and I don't know what purposes this is needed for.
This is initialization code, introduced in the language (if I remember correctly) to allow for native types to be treated like generic types, when writing templates and classes.
Here's an example:
struct S { int x; S(int a) : x(a) {} }; // structure with constructor taking an int
// observe constructor syntax for int member
// example factory function (not very usefull in practice but good example)
template<typename T>
T make_instance( int x ) { return T(x); /* use old syntax for constructor call */ }
auto s = make_instance<S>(10); // create S instance with value 10
auto i = make_instance<int>(10); // create integer with value 10
In this example, the template constructs an instance of any type that supports a constructor taking an int. The second example (initializing an int
) will only work if the language supports initializing an integer with the following syntax:
int x(10);
This is constructor syntax. The language also supports calling the "default constructor" for a native value (i.e. calling the constructor with no arguments, which for an int
sets the value to zero). This is the case in your example (calling default implicit int "constructor").