c++ - 输入迭代器的值初始化

标签 c++ istream-iterator value-initialization

我正在阅读“Accelerated C++”一书的第 8 章。 8.3 节是关于输入和输出迭代器的:

vector<int> v; // read ints from the standard input and append them to v
copy(istream_iterator<int>(cin), istream_iterator<int>(), back_inserter(v));

[...]

The second argument to copy creates a default (empty) istream_iterator, which is not bound to any file. The istream_iterator type has a default value with the property that any istream_iterator that has reached end-of-file or is in an error state will appear to be equal to the default value. Therefore, we can use the default value to indicate the "one-past-the-end" convention for copy.

我是这样理解的:istream_iterator是一个模板类,istream_iterator是模板的一个实例。编写 istream_iterator() 会触发 istream_iterator 对象的值初始化,这意味着零初始化 + 调用隐式默认构造函数 (http://en.cppreference.com/w/cpp/language/value_initialization)。我认为 istream_iterator 对象的默认初始化也可以工作(触发对默认构造函数的调用),所以我尝试了这个:

vector<int> v; // read ints from the standard input and append them to v
copy(istream_iterator<int>(cin), istream_iterator<int>, back_inserter(v));

但这不编译:

error: expected primary-expression before ‘,’ token

我不明白这是怎么回事。欢迎任何解释。

最佳答案

没有办法默认初始化,而不是值初始化,一个临时的。虽然表达式 type() 创建了一个值初始化的临时值,但类型名称本身并不是一个有效的表达式。

但是,对于声明默认构造函数的任何类型(像这个),默认初始化和值初始化是等价的;在调用非隐式构造函数之前没有零初始化。

关于c++ - 输入迭代器的值初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18019489/

相关文章:

c++ - 使用同步或异步的单线程连接多个客户端?

c++ - 用多个线程填充 vector

C++ 入门第 5 版 : Stream iterators and Sales_item

c++ - C++中istream_iterator的奇怪结果

c++ - 想要在发票程序中使用 while 或 for 循环将字符串项与 C++ 中的整数值匹配

c++ - Boost::asio::async_read() 缓冲区损坏问题

c++ - 在 std::vector 构造函数中使用 '{}' 作为结束迭代器

d - 诠释我=诠释(); D 会发生什么?

c++ - 在不破坏遗留代码的情况下将成员添加到现有结构

c++ - 对空的用户定义构造函数如何初始化非静态非 POD 成员变量感到困惑