In C ++, is it good to implement an iterator interface in which promoting the invalidity of the "current" element?

I am developing a C ++ interface that allows the user to iterate through objects decoded from a file. This decoding process is somewhat slow.

I am considering an iterator interface for this, but I want to avoid an unnecessary copy, so I am thinking about (user side):

for (const auto& object : file) {
    // you can access the members of `object` here
    std::cout << object.whatever() << std::endl;

    // you can copy `object` here
    myObjectCopy = object;

    // you CANNOT do this because `object` changes
    // as soon as the iterator advances
    myObjectPtr = &object;
}

object in the previous usage example, is a reference to an object internal to the iterator instance.

It is not right? What other idiomatic interfaces would you suggest here?

I thought about the stream interface (I think std::istream), but AFAIK, data reading methods also return copies (they extract characters).

+4
2

, , .

std::iterator<std::input_iterator_tag, decoded_object_type>. operator* , operator++; operator++ operator*, , , .

+7

, . Iostream : , , , , .

+2

Source: https://habr.com/ru/post/1659838/


All Articles