Namespaces
Variants

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

From cppreference.net
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::cin std::cerr 。类似地,其宽字符版本 std::wcout 被关联到 std::wcin std::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() 是一个 无格式输出函数 ,因此在被调用时会创建哨兵对象。当对流对象调用 flush() 时, 哨兵对象的构造函数 会调用其关联流的 flush() ,而该 flush() 又会构造另一个哨兵对象,其构造函数将调用该流关联流的 flush() ,依此类推。因此,如果流 a b (直接或间接)相互关联,调用 a. flush ( ) 最终将调用 b. flush ( ) ,而后者最终又会调用 a. flush ( ) ,从而导致无限循环。