【问题标题】:Why do many standard implementations allow a value to be directly assigned to an ostream_iterator?为什么许多标准实现允许将值直接分配给 ostream_iterator?
【发布时间】:2012-03-27 09:30:17
【问题描述】:

我尝试过的所有标准实现都允许将值分配给std::ostream_iterator,而无需在分配之前取消引用它们。尽管标准算法在分配之前取消引用迭代器,但我想知道为什么有些实现不只是静态地禁止分配(在代理类的帮助下),这样编译就会失败,所以用户知道如果将此类分配移植到另一个实现由于某些原因不允许分配,则可能会发生错误。 一般来说,在实现标准功能时,将实现限制为仅允许标准明确提及的功能是否是一种好习惯?

#include <iterator>
#include <string>
#include <iostream>

using namespace std;

int main() {
    ostream_iterator<string> o(cout);
    o = "Hello World\n"; // o is not dereferenced! It compiles with my GCC environment
    o++; // to make sure the implementation writes to cout
}

【问题讨论】:

  • In general, when implementing a standard functionality, is it a good practice to limit the implementation to only allow what is explicitly mentioned by the standard? 是的,当然。

标签: c++ stl iostream


【解决方案1】:

允许此赋值的运算符重载由 C++ 语言标准指定。因此,C++ 标准库实现必须提供它。

重载指定如下(来自 C++11 §24.6.2.2/1):

ostream_iterator& operator=(const T& value);

效果:

*out_stream << value;
if(delim != 0)
    *out_stream << delim;

return (*this);

TT 实例化 ostream_iterator。在您的示例中,它是 string。)

【讨论】:

    【解决方案2】:

    流迭代器实际上只是假的迭代器。插入发生在分配ostream_iterator 时,提取发生在取消引用istream_iterator 时。 ostream_iteratoroperator*() 实际上被指定为只返回 *this 的无操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2010-11-13
      • 2021-11-01
      • 1970-01-01
      相关资源
      最近更新 更多