中对静态缓冲区执行字符串格式化

中对静态缓冲区执行字符串格式化

本文介绍了如何在 C++ 中对静态缓冲区执行字符串格式化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理具有非常高性能要求的一段代码.我需要执行一些格式化的字符串操作,但我试图避免内存分配,甚至是内部库分配.

I am working in a section of code with very high performance requirements. I need to perform some formatted string operations, but I am trying to avoid memory allocations, even internal library ones.

过去,我会做类似以下的事情(假设 C++11):

In the past, I would have done something similar to the following (assuming C++11):

constexpr int BUFFER_SIZE = 200;
char buffer[BUFFER_SIZE];
int index = 0;
index += snprintf(&buffer[index], BUFFER_SIZE-index, "Part A: %d\n", intA);
index += snprintf(&buffer[index], BUFFER_SIZE-index, "Part B: %d\n", intB);
// etc.

我更愿意使用所有 C++ 方法(例如 ostringstream)来执行此操作,而不是使用旧的 C 函数.

I would prefer to use all C++ methods, such as ostringstream, to do this instead of the old C functions.

我意识到我可以使用 std::string::reserve 和 std::ostringstream 提前获取空间,但这仍将执行至少一次分配.

I realize I could use std::string::reserve and std::ostringstream to procure space ahead of time, but that will still perform at least one allocation.

大家有什么建议吗?

提前致谢.

推荐答案

感谢所有提出建议的人(甚至在评论中).

My thanks to all that posted suggestions (even in the comments).

我很欣赏 SJHowe 的建议,这是解决问题的最简洁的方法,但我希望通过这次尝试做的一件事是开始为未来的 C++ 编码,而不是使用任何已弃用的东西.

I appreciate the suggestion by SJHowe, being the briefest solution to the problem, but one of the things I am looking to do with this attempt is to start coding for the C++ of the future, and not use anything deprecated.

我决定采用的解决方案源于 Remy Lebeau 的评论:

The solution I decided to go with stems from the comment by Remy Lebeau:

#include <iostream>  // For std::ostream and std::streambuf
#include <cstring>   // For std::memset

template <int bufferSize>
class FixedBuffer : public std::streambuf
{
public:
   FixedBuffer()
      : std::streambuf()
   {
      std::memset(buffer, 0, sizeof(buffer));
      setp(buffer, &buffer[bufferSize-1]);         // Remember the -1 to preserve the terminator.
      setg(buffer, buffer, &buffer[bufferSize-1]); // Technically not necessary for an std::ostream.
   }

   std::string get() const
   {
      return buffer;
   }

private:
   char buffer[bufferSize];
};

//...

constexpr int BUFFER_SIZE = 200;
FixedBuffer<BUFFER_SIZE> buffer;
std::ostream ostr(&buffer);

ostr << "PartA: " << intA << std::endl << "PartB: " << intB << std::endl << std::ends;

这篇关于如何在 C++ 中对静态缓冲区执行字符串格式化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 12:18