Modern C++ idiom for allocating / deallocating an I/O buffer

后端 未结 5 1471
情歌与酒
情歌与酒 2020-12-31 00:00

For I/O work, I need to read N bytes into a buffer. N is known at run time (not compile time). The buffer size will never change. The buffer is passed to other routines t

5条回答
  •  再見小時候
    2020-12-31 00:26

    I think its common to use a std::vector for this.

    The benefits of using std::vector over an manually allocated char buffer are copy semantics (for passing to functions that wish to modify the data for their own purposes or when returning the data to a calling function).

    Also a std::vector knows its own size reducing the number of parameters that need passing to processing functions and eliminating a source of bugs.

    You have complete control over how the data is passed to other functions - either by reference or const reference as appropriate.

    If you need to call an older c-style function with a plain char* and length you can easily do that too:

    // pass by const reference to preserve data
    void print_data(const std::vector& buf)
    {
        std::cout.fill('0');
        std::cout << "0x";
        for(auto c: buf)
            std::cout << std::setw(2) << std::hex << int(c);
        std::cout << '\n';
    }
    
    // pass by reference to modify data
    void process_data(std::vector& buf)
    {
        for(auto& c: buf)
            c += 1;
    }
    
    // pass by copy to modify data for another purpose
    void reinterpret_data(std::vector buf)
    {
        // original data not changed
        process_data(buf);
        print_data(buf);
    }
    
    void legacy_function(const char* buf, std::size_t length)
    {
        // stuff
    }
    
    int main()
    {
        std::ifstream ifs("file.txt");
    
        // 24 character contiguous buffer
        std::vector buf(24);
    
        while(ifs.read(buf.data(), buf.size()))
        {
            // changes data (pass by reference)
            process_data(buf);
    
            // modifies data internally (pass by value)
            reinterpret_data(buf);
    
            // non-modifying function (pass by const ref)
            print_data(buf);
    
            legacy_function(buf.data(), buf.size());
        }
    }
    

提交回复
热议问题