Address of a dereferenced InputIterator? The case of istream_iterator

喜欢而已 提交于 2020-01-03 05:34:06

问题


I have a legacy code in which the interface is defined for pointer. I am trying to adapt some functions to take iterators, e.g. forward iterators.

Is one allowed to take the address of the element dereferenced by InputIterator such as istream_iterator?

The result is a temporary and has to be is somewhere in memory for the life of the call, but I am not sure.

The following example uses double, but the type can be more complicated (large).

#include<iostream>
#include<iterator>
#include<sstream>

void f_legacy(double const* t){
    std::cout << *t << std::endl;
};

void f(std::istream_iterator<double> it){
    f_legacy(std::addressof(*it)); // OK????
    // to avoid a copy:     auto v = *it; f_legacy(std::addressof(v));
}

int main(){
    double d = 5.;
    std::istringstream iss("1 2 3");
    std::istream_iterator<double> it(iss);
    f_legacy(&d);
    f(it);
}

回答1:


It is always legal to take the address of an lvalue.

Since istream_iterator::operator* returns a reference, it must be returning a reference to an object that survives beyond the function call, and until the iterator is advanced. So your code is well-defined.



来源:https://stackoverflow.com/questions/49267066/address-of-a-dereferenced-inputiterator-the-case-of-istream-iterator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!