1 2
|
explicit vector( int theSize = 0 ) : currentSize( theSize )
{ objects = new Object[ currentSize ]; }
|
The keyword explicit means that any type conversions to match this signature must be made explicitly. In other words, it prevents implicit conversions. The snippet is constructing a vector to a given size. Now, if the user passed something else (not a size) that can be converted to an int, it will cause a compiler error.
Without the explicit keyword, a user could mistakenly pass something else to this constructor and it would compile. This kind of oversight can cause subtle bugs that can go unnoticed. Off the top of my head (not tested, of course), consider something like this example:
1 2 3 4 5 6
|
int * p = new p();
*p = 10;
// ...
vector v( p );
// ...
delete p;
|
In this example, the user meant to pass *p, which is 10, but instead the pointer address is being converted to an int and constructing a huge random sized vector! (Note that this probably wouldn't be an implicit conversion unless the platform's pointer size = int size.)
As for the duplicated code with const's, that is for const correctness. The user of the vector may want to inspect a value read-only rather than modifying it. Such uses (const or not) depend on the context of the call so both cases are available.