Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
174 views
in Technique[技术] by (71.8m points)

c++ - How does std::end know the end of an array?

std::begin and std::end know the beginning and end of a container or an array.

It so easy to know the end and begin of a vector for example because it is a class that gives this information. But, how does it know the end of an array like the following?

int simple_array[5]{1, 2, 3, 4, 5};
auto beg=std::begin(simple_array);
auto en=std::end(simple_array);

std::begin is not that hard to know where the array start. But how does it know where it ends? Will the constant integer 5 be stored somewhere?

I would appreciate if I got an answer with some low-level information.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

But, how does it know the end of an array

It uses a template non-type parameter to deduce the size of the array, which can then be used to produce the end pointer. The C++11 signature from the cppreference section for std::end is as follows:

template< class T, std::size_t N >
T* end( T (&array)[N] );

As hvd notes, since it is passed by reference this prevents decay to a pointer.

The implementation would be something similar to:

template< class T, std::size_t N >
T* end( T (&array)[N] )
{
    return array + N ;
}

Is the constant integer 5 will be stored some where?

5 or N is part of the type of the array and so N is available at compile time. For example applying sizeof to an array will give us the total number of bytes in the array.

Many times we see an array passed by value to a function. In that case, the array decays to a pointer to type stored in the array. So now the size information is lost. Passing by reference allows us to avoid this loss of information and extract the size N from the type.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...