Teronary operator

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 ? new int[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);
    }
No. It says:

if mSize is not equal to 0 then return new int[mSize] else return nullptr

However, it doesn't actually return the value but instead the selected branch becomes the value of the TERNARY expression.
Last edited on
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.

whether or not mSize has a value

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 )
    return false;
  else
    return true;
}

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
thanks guys that makes sense! :)
Topic archived. No new replies allowed.