template<class ForwardIterator>
inline void _destroy_aux(ForwardIterator first, ForwardIterator last, _false_type)
{
for (; first != last; ++first)
{
destroy(&*first);
}
}
其中destroy函数为
template<class T>
inline void destroy(T *ptr)
{
ptr->~T();
}
问题是,destroy(&*first)中:
first取了值又取了地址,&*first不就等于first吗;
于是我写了一小段测试代码:
//vector的头指针
std::vector<int> v;
v.push_back(1);
auto first = v.begin();
std::cout /*<< first */<< *first << " " << &*first << std::endl;
//内置int的指针
int n = 1;
int *p = &n;
std::cout << p << " " << *p << " " << &*p << std::endl;
发现vector的指针直接输出会出错,但是经过&*处理就正常输出,而vector源码中的指针用的是内置的,也就是说测试代码中的first本质应该是int指针。这是怎么回事。
Iterator simply wraps the int* raw pointer
first cannot be output simply because there is no overloaded disjunction operator
first becomes int after dereferencing in this way, which is different from the type of first itself, so &first can naturally output
The iterator has the
*
operator (returns a reference). If you get the address, it is equivalent to getting the pointer.The iterator itself is not equal to the pointer, and can be understood as something similar to the pointer. But it’s not. Try to think about it, the memory of
vector
is continuous, then if I use a pointer as an iterator, the++
operator can work normally; but if I use alist
or amap
, you can’t just++
casually, there is logic in the++
operator. You can look at the code carefully.