How are you supposed to use set_rdbuf()?

  c++, ifstream, visual-c++

So I am creating a class that inherits from ifstream, and that gives me acces to the protected function set_rdbuf, and at first I just thought it allowed you to set your own filebuf that then would be used, but that does not seem to work for me. I wrote the following code:

class A : public std::fstream {
private:
    std::filebuf m_file_buf;

public:
    A() {
        if (!m_file_buf.open("test_file.txt", ios_base::out | ios_base::in)) {
            std::cout << "something went wrong";
        }
        // std::fstream::rdbuf()->swap(m_file_buf);
        std::fstream::set_rdbuf(&m_file_buf);
        std::cout << "m_ file buff is: " << m_file_buf.is_open() << "n";
        std::cout << "rd file buff is: " << std::fstream::rdbuf()->is_open() << "n";
        std::cout << "we are: " << std::fstream::is_open() << "n";
    }
};
int main() {
    A a;

    return 0;
}

This will log:

m_ file buff is: 1
rd file buff is: 0
we are: 0

I was under the assumption that when I called rdbuf() I would then get the one I had set it to. However, if I use the swap function that rdbuf() provides, then it prints as I expect it to

class A : public std::fstream {
private:
    std::filebuf* m_file_buf;

public:
    A() {
        m_file_buf = new std::filebuf();
        if (!m_file_buf->open("test_file.txt", ios_base::out | ios_base::in)) {
            std::cout << "something went wrong";
        }
        std::fstream::rdbuf()->swap(*m_file_buf);
        std::cout << "m_ file buff is: " << m_file_buf->is_open() << "n";
        std::cout << "rd file buff is: " << std::fstream::rdbuf()->is_open() << "n";
        std::cout << "we are: " << std::fstream::is_open() << "n";
        // Get it back again as we swapped it out
        m_file_buf = std::fstream::rdbuf();
    }
};
int main() {
    A a;

    return 0;
}
m_ file buff is: 0
rd file buff is: 1
we are: 1
//and when I at the end swap back, everything is 1/open

I swited to pointer in the swap code so that I could point to the return of rdbuf()

This was compiled on MSVC version 19.28 with arg /std:c++17

So am I wrong is how set_rdbuf is supposed to be used, or is there something else I am doing wrong?

Source: Windows Questions C++

LEAVE A COMMENT