1

I have a question on the implementation of vector in EASTL. The link is here.

Namely, on the method size(). Here is what it looks like:

template <typename T, typename Allocator>
inline typename vector<T, Allocator>::size_type
vector<T, Allocator>::size() const
{
    return (size_type)(mpEnd - mpBegin);  
}

size_type is uint32_t, mpBegin/mpEnd are T* pointers.

I do not understand how the cast to uint32_t from (mpEnd - mpBegin) equals the number of elements in a vector. Shouldn't it be divided by sizeof(T)? Otherwise we just get the size in bytes of all the elements in the vector?

What am I missing?

EDIT: Unless, the EASTL vector dosn't follow the stl defintion of a vector, but I couldn't find any data on it and its supposedly be possible to replace stl vector with eastl vector

KaiserJohaan
  • 9,028
  • 20
  • 112
  • 199

2 Answers2

2

It's not the cast that causes the operation to equal the number of elements in the array. Pointer subtraction already does the right thing here. When you subtract one pointer from another, the size of the types they point to is taken into account. There is no need to divide by sizeof(T). It has always been this way, even in C. The cast simply converts it to the right integer type for the return value, if it's not already.

Benjamin Lindley
  • 101,917
  • 9
  • 204
  • 274
1

The size is only in bytes if you are using char* or possibly void*. Else, it is in sizeof(T). Since mpEnd and mpBegin are T*.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 1
    `void*` doesn’t allow pointer arithmetic. And even with `char*` it’s still in units of `sizeof(T)`, which just happens to be 1. – Konrad Rudolph Apr 14 '12 at 20:16