问题描述
对于I / O工作,我需要将N个字节读入缓冲区。 N在运行时是已知的(不是编译时间)。缓冲区大小永远不会改变。缓冲区被传递给其他例程来压缩,加密等:它只是一个字节序列,没有高于这个。
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 to compress, encrypt, etc: it's just a sequence of bytes, nothing higher than that.
在C中,我将分配缓冲区 malloc
,然后免费
。但是,我的代码是现代C ++,肯定没有 malloc
到位,很少原始新
和 delete
:我正在大量使用RAII和 shared_ptr
。然而,这些技术似乎不适合这个缓冲区。它只是一个固定长度的字节缓冲区,接收I / O并使其内容可用。
In C, I would allocate the buffer with malloc
and then free
it when I'm done. However, my code is modern C++, certainly no malloc
s in place, and very few raw new
and delete
: I'm making heavy use of RAII and shared_ptr
. None of those techniques seem appropriate for this buffer, however. It's just a fixed length buffer of bytes, to receive I/O and make its contents available.
这是一个现代的C ++成语吗?或者,对于这个方面,我应该只是坚持好ol' malloc
?
Is there a modern C++ idiom to this elegantly? Or, for this aspect, should I just stick with good ol' malloc
?
推荐答案
size_t n = /* size of buffer */;
auto buf_ptr = std::make_unique<uint8_t[]>(n);
auto nr = ::read(STDIN_FILENO, buf_ptr.get(), n);
auto nw = ::write(STDOUT_FILENO, buf_ptr.get(), nr);
// etc.
// buffer is freed automatically when buf_ptr goes out of scope
请注意,上面的结构将value-initialize(零输出)缓冲区。如果你想跳过初始化保存几个周期,你必须使用由lisyarus给出的稍微夸张的形式:
Note that the above construct will value-initialize (zero out) the buffer. If you want to skip the initialization to save a few cycles, you'll have to use the slightly uglier form given by lisyarus:
std::unique_ptr<uint8_t[]> buf_ptr(new uint8_t[n]);
这篇关于现代C ++成语用于分配/取消分配I / O缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!