取消引用的InputIterator的地址? istream_iterator的情况 [英] Address of a dereferenced InputIterator? The case of istream_iterator

查看:217
本文介绍了取消引用的InputIterator的地址? istream_iterator的情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个遗留代码,其中为指针定义了接口。
我正在尝试适应某些功能以采用迭代器,例如

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.

允许使用InputIterator取消引用的元素的地址,例如 istream_iterator

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.

下面的示例使用 double ,但是类型可能更复杂(大)。

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);
}


推荐答案

服用总是合法的左值的地址。

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

由于 istream_iterator :: operator * 返回一个引用,因此它必须返回一个引用到一个对象,该对象在函数调用之后仍然存在,并且直到迭代器被推进为止。因此,您的代码定义明确。

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.

这篇关于取消引用的InputIterator的地址? istream_iterator的情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆