c++ - 从空缓冲区构造 `std::ostream` 是否有效?

标签 c++ c++11 std iostream

考虑以下几点:

std::ostream out(nullptr);

这合法且定义明确吗?


如果我现在这样做呢:

out << "hello world\n";

这是否合法且定义明确?如果是这样,大概是一种无操作?

最佳答案

是的,实例化该流是合法且定义明确的。您可以安全地将其与另一个流交换,或者稍后给它一个新指针(这次指向现有缓冲区)。输出操作本身确实是空操作。

原因如下:

  1. 构造没有非空前置条件,只有这个后置条件:

    [C++11: 27.7.3.2/2]: Postcondition: rdbuf() == sb.

  2. 有趣的是,它明确指出不得对 sb 执行任何操作。在构造函数中:

    [C++11: 27.7.3.2/4]: Remarks: Does not perform any operations on rdbuf().

  3. 但也要注意:

    [C++11: 27.7.3.2/1]: Effects: Constructs an object of class basic_ostream, assigning initial values to the base class by calling basic_ios<charT,traits>::init(sb) (27.5.5.2).

  4. 那个init(sb) call具有设置badbit的效果直播时sb为空:

    [C++11: 27.5.5.2/3]: Postconditions: The postconditions of this function are indicated in Table 128.

    [C++11: Table 128]: [..] rdstate(): goodbit if sb is not a null pointer, otherwise badbit. [..]

  5. 输出操作导致相当于取消引用空指针的操作:

    [C++11: 27.7.3.1/2]: Two groups of member function signatures share common properties: the formatted output functions (or inserters) and the unformatted output functions. Both groups of output functions generate (or insert) output characters by actions equivalent to calling rdbuf()->sputc(int_type). They may use other public members of basic_ostream except that they shall not invoke any virtual members of rdbuf() except overflow(), xsputn(), and sync().

    除了它从来没有走到这一步,因为对于basic_ostream::sentry build :

    [C++11: 27.7.3.4/3]: If, after any preparation is completed, os.good() is true, ok_ == true otherwise, ok_ == false.

    对于explicit operator basic_ostream::sentry::bool() const; :

    [C++11: 27.7.3.4/5]: Effects: Returns ok_.

    和:

    [C++11: 27.7.3.7/1]: Each unformatted output function begins execution by constructing an object of class sentry. If this object returns true, while converting to a value of type bool, the function endeavors to generate the requested output. [..]

    ...这意味着当 badbit 时根本不发生任何输出操作。已经设置好了。

This was also the case in C++03.

关于c++ - 从空缓冲区构造 `std::ostream` 是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25690636/

相关文章:

c++ - 从专用模板方法调用非专用模板方法

c++ - 静态结构成员获取 “undefined reference” 。不知道为什么

c++ - 为什么 Microsoft Visual Studio 找不到 <stdint.h>?

c++ - 我可以将什么用作 RAII+关注点分离的标准 C++ 基类

c++ - vector 无效分配大小

c++ - 主机和目标的 Makefile

c++ - qt Creator qt5.1 vs2010使用静态库时链接器错误

c++ - 特化模板覆盖函数/避免对象切片

c++ - 复制具有线程安全规则建议的非const参数的构造函数?

c++ - 在编译时将 std::array 转换为另一种数据类型?