问题
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