【问题标题】:Why does this RAII cout redirector not work:为什么这个 RAII cout 重定向器不起作用:
【发布时间】: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 规则...

标签: c++ iostream


【解决方案1】:

我认为cout_redirect(buffer.rdbuf()); 只是创建了在; 上删除的临时对象。试试cout_redirect cr(buffer.rdbuf());

在实践中,最好将这样的东西包装在宏中以自动生成唯一名称。

【讨论】:

    【解决方案2】:

    cout_redirect(buffer.rdbuf());构造一个临时的cout_redirect对象,重定向cout,然后销毁临时对象,恢复cout

    你的意思是cout_redirect guard(buffer.rdbuf());吗?

    【讨论】:

    • @Spacemoose 旁注:您可以通过删除所有 cout 重定向并仅在构造函数/析构函数中打印调试消息来进一步减少测试用例。 :-)
    • 是的...我能说什么。我今天过得很糟糕。
    猜你喜欢
    • 2011-08-21
    • 2017-06-12
    • 1970-01-01
    • 2016-05-14
    • 1970-01-01
    • 2016-09-13
    • 2018-02-15
    • 1970-01-01
    • 2012-07-05
    相关资源
    最近更新 更多