将流绑定到自身

Tying a stream to itself

为什么这段代码 运行 在 g++ 和 clang 上成功 (libstdc++) but give a segmentation fault with libc++:

#include <iostream>

int main()
{
    std::cout.tie(&std::cout);
    std::cout << 123;
}

我认为应该发生的是 std::cout.flush() 应该在输出实际发生之前被调用。为什么这会产生分段错误?

[ostream.unformatted]/p7:

basic_ostream& flush();

7 Effects: Behaves as an unformatted output function [...]

[ostream.unformatted]/p1:

Each unformatted output function begins execution by constructing an object of class sentry.

[ostream::哨兵]/p2:

explicit sentry(basic_ostream<charT,traits>& os);

2 If os.good() is nonzero, prepares for formatted or unformatted output. If os.tie() is not a null pointer, calls os.tie()->flush().324

3 [...]

324 The call os.tie()->flush() does not necessarily occur if the function can determine that no synchronization is necessary.

如果你将流绑定到自身,然后为了刷新流,它构造一个 sentry,它试图刷新流,它构造一个 sentry,它试图刷新流,它构造一个 sentry,它试图刷新流,它构造一个 sentry......我想你明白这是怎么回事了。

如果你(不幸)走运,实施可能会根据脚注 324 在某处跳过 flush() 调用;否则,您将看到该站点的标题。