简体   繁体   中英

Error trying to implement STL iterators

I am fairly new to STL and iterators. I've used them quite frequently but am only now gaining an understanding of how they really work. For an assignment, I am tasked with re-writing a few STL iterators to understand what is going on under the hood. I'm midway through my insert_iterator :

template <class Container>
class m_insert_iterator : public std::iterator<output_iterator_tag, void, 
void, void, void>
{
protected:
    Container* container;
    typename Container::iterator it;

public:
    typedef Container container_type;

    // Constructor:
    m_insert_iterator(Container &x, typename Container::iterator i)
    {
        *container = x;
        it = i;
    }

    // Assignment operator:
    m_insert_iterator<Container> &operator=(const typename Container::value_type &value)
    {
        it = container->insert(this, value);
        ++it;
        return *this;
    }

    // No-ops:
    m_insert_iterator<Container> &operator*() { return *this };
    m_insert_iterator<Container> &operator++() { return *this };
    m_insert_iterator<Container> &operator++(int) { return *this };
};

int main()
{
    vector<int> v{ 2, 3, 4 };
    m_insert_iterator<vector<int>> ins_it(v, v.begin());
    ins_it = 1;

    for (int i = 0; i < v.size(); i++)
    {
         cout << v[i] << " ";
    }

    system("pause");
}

Whenever I call the constructor, my program crashes on *container = x . In the debugger I get an error message reading '0xC0000005: Access violation reading location 0x00000000.' Why is this happening?

Your error is in your understanding of pointers, you can't assign anything to an uninitialized pointer. so you can't assign a reference to an uninitialized pointer in your constructor:

*container = x;  // container is uninitialized, so this function will generate an AccessViolation

Instead you should use it as

container = std::addressof(x);

In this case you initialize your pointer with address of the reference that passed to you, but in your case you are trying to copy the reference to address that your pointer is pointing to it and since your pointer is not initialized, you are trying to write to an unknown location of the memory.

In best case you get an AccessDenied or something like that but you can also cause strange errors if it happen to write to a memory that is writable to your program. For example you may override value of one or more of your variables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM