stl - C++ construct源码中 destroy问题
伊谢尔伦
伊谢尔伦 2017-04-17 13:18:35
0
2
561
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指针。这是怎么回事。
伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(2)
洪涛

Iterator simply wraps the int* raw pointer

    std::cout /*<< first */<< *first << " " << &*first << std::endl;

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


int main() {
    std::vector<int> vec;

    vec.push_back(1);   

    auto f = vec.begin();

    // Iterator的指针 是protected的,方便起见,直接转换输出
    std::cout <<"f ->"<<*((int*)&f)<<" *f -> "<<*f<< &*f -> "<<&*f<<std::endl;
    
    return 0;
}

伊谢尔伦

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 a list or a map , you can’t just ++ casually, there is logic in the ++ operator. You can look at the code carefully.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template