here is the snippet of code I am referring to which is in the copy constructor,I don't understand what the terenry operator is doing hereit is saying if mSize is equal to new int[mSize] let mSize = new int[mSize] else set it to a nullptr,so how does this even work?
1 2 3 4 5 6 7 8 9
dumb_array(const dumb_array& other)
: mSize(other.mSize),
mArray(mSize ? newint[mSize] : nullptr),
{
// note that this is non-throwing, because of the data
// types being used; more attention to detail with regards
// to exceptions must be given in a more general case, however
std::copy(other.mArray, other.mArray + mSize, mArray);
}
I don't understand what the terenry operator is doing hereit is saying if mSize is equal to new int[mSize] let mSize = new int[mSize] else set it to a nullptr,so how does this even work?
It is not checking mSize to new int[mSize] it is checking whether or not mSize has a value. If it does it creates an array of size mSize, otherwise assigns nullptr to the pointer mArray, this is assuming that mSize is some kind of unsigned type.
Assuming that mSize is integer type, then it always has some value. (There is no NaN integer.)
The mSize is used as condition expression.
1 2 3
( mSize )
// is essentially
( static_cast<bool>(mSize) )
For integer types that conversion is like:
1 2 3 4 5 6
bool foo( T mSize ) {
if ( 0 == mSize )
returnfalse;
elsereturntrue;
}
Therefore,
1 2 3
( mSize )
// is like
( 0 != mSize )
IF mSize is not 0
THEN dynamically allocate block of memory (for mSize ints) and initialize dumb_array::mArray with the address of the block
ELSE initialize dumb_array::mArray with nullptr