简体   繁体   English

C ++ std :: cout缓冲区重定向seg错误

[英]C++ std::cout buffer redirect seg fault

Hi So i wrote some simple code to redirect the std::cout output to a std::ostringstream and it works fine from within main eg. 嗨,所以我写了一些简单的代码,将std :: cout输出重定向到std :: ostringstream,并且在main eg中可以正常工作。

#include <iostream>
#include <sstream>

int main(){
  std::ostringstream m_oss;
  std::streambuf *m_sbuf, *bcout;

  m_sbuf=m_oss.rdbuf();
  bcout = std::cout.rdbuf();
  std::cout.rdbuf(m_sbuf);

  std::cout<<"hello world"<<std::endl;

  std::cout.rdbuf(bcout);        // restore cout's original streambuf

  std::cout<<m_oss.str();

  return 0;
}

however if i want to do the same redirect within a class then I get a Seg fault on the line 'std::cout.rdbuf(m_sbuf);' 但是,如果我想在一个类中执行相同的重定向,那么我会在“ std :: cout.rdbuf(m_sbuf);”行上遇到Seg错误。

eg 例如

#include <iostream>
#include <sstream>

class test {

  public:
     std::ostringstream m_oss;
     std::streambuf *m_sbuf, *bcout;

     test(){

        m_sbuf=m_oss.rdbuf();
        bcout = std::cout.rdbuf();
        std::cout.rdbuf(m_sbuf);
     }


     void print(){

       std::cout.rdbuf(bcout);        // restore cout's original streambuf
       std::cout<<m_oss.str();

     }

};

int main(){

  test t();

  std::cout<<"Hello world"<<std::endl;

  t.print();     

  return 0;
}

any ideas how i can encapsulate this in a class as i don't really want the end user to see it and get confused? 任何想法如何将其封装在类中,因为我真的不希望最终用户看到它并感到困惑?

Use this to instantiate object t : 使用它实例化对象t

test t;

not

test t();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM