【发布时间】:2018-03-06 15:25:04
【问题描述】:
我想使用这个答案中给出的方法:https://stackoverflow.com/a/5419388/2050788,但显然我遗漏了一些东西,因为 cout 最终不会被重定向。有人可以解释我缺少什么吗?
这是一个最小的可编译示例:
#include <sstream>
#include <streambuf>
#include <iostream>
struct cout_redirect {
cout_redirect( std::streambuf * new_buffer )
: old( std::cout.rdbuf( new_buffer ) )
{ }
~cout_redirect( ) {
std::cout.rdbuf( old );
}
private:
std::streambuf * old;
};
void no_guard() {
std::cout << "No RAII" << std::endl;
std::stringstream buffer;
std::streambuf *old = std::cout.rdbuf(buffer.rdbuf());
std::cout << "Bla" << std::endl;
std::cout.rdbuf(old);
std::cout << "Text = " << buffer.str() << std::endl;
}
void with_guard()
{
std::cout << "Using RAII" << std::endl;
std::stringstream buffer;
cout_redirect(buffer.rdbuf());
std::cout << "Bla";
}
int main() {
no_guard();
with_guard();
}
输出是:
No RAII
Text = Bla
Using RAII
Bla
No RAII 案例按预期工作。在 RAII 情况下,我希望没有输出,因为 cout 应该被重定向到 stringstream 缓冲区。我错过了什么? (使用 gcc 7.3.1 与 g++ -Wall test.cpp 编译)。
编辑:好吧,我真的很愚蠢——但我已经足够大了,可以承认这一点,并将其留在这里以提醒我的错误。
【问题讨论】:
-
还请注意,您可能应该删除
cout_redirect的复制构造函数。 3/5/0 规则...