命名空间
变体
操作

std::basic_ios<CharT,Traits>::tie

来自 cppreference.cn
< cpp‎ | io‎ | basic ios
 
 
 
 
std::basic_ostream<CharT, Traits>* tie() const;
(1)
std::basic_ostream<CharT, Traits>* tie( std::basic_ostream<CharT, Traits>* str );
(2)

管理绑定的流。绑定的流是一个输出流,它与流缓冲区(rdbuf())控制的序列同步,也就是说,在对 *this 进行任何输入/输出操作之前,会在绑定的流上调用 flush()

1) 返回当前绑定的流。如果没有绑定的流,则返回空指针。
2) 将当前绑定的流设置为 str。返回操作前的绑定的流。如果没有绑定的流,则返回空指针。如果 str 不为空,并且从 str->tie() 开始遍历绑定的流对象的链表可以访问到 tie(),则行为未定义。

目录

[编辑] 参数

str - 要设置为绑定的流的输出流

[编辑] 返回值

绑定的流,如果没有绑定的流,则为空指针。

[编辑] 异常

可能抛出实现定义的异常。

[编辑] 注意

默认情况下,标准流 std::cout 绑定到 std::cinstd::cerr。类似地,它的宽字符对应物 std::wcout 绑定到 std::wcinstd::wcerr

[编辑] 示例

#include <fstream>
#include <iomanip>
#include <iostream>
#include <string>
 
int main()
{
    std::ofstream os("test.txt");
    std::ifstream is("test.txt");
    std::string value("0");
 
    os << "Hello";
    is >> value;
 
    std::cout << "Result before tie(): " << std::quoted(value) << "\n";
    is.clear();
    is.tie(&os);
 
    is >> value;
 
    std::cout << "Result after tie(): " << std::quoted(value) << "\n";
}

输出

Result before tie(): "0"
Result after tie(): "Hello"

[编辑] 缺陷报告

下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。

缺陷报告 应用于 发布时的行为 正确的行为
LWG 835 C++98 两个流可能相互绑定[1]
(直接或通过另一个中间流对象)
在这种情况下行为未定义
  1. std::basic_ostream::flush() 是一个 UnformattedOutputFunction,因此在调用它时会创建一个哨兵对象。当在一个流对象上调用 flush() 时,哨兵对象的构造函数将在其绑定的流上调用 flush(),而该 flush() 将构造另一个哨兵对象,其构造函数将在此流的绑定的流上调用 flush(),依此类推。因此,如果流 ab (直接或间接) 相互绑定,则调用 a.flush() 最终将调用 b.flush(),后者最终将调用 a.flush(),从而导致无限循环。