如何在C++中对静态缓冲区执行字符串格式化?
How do I perform string formatting to a static buffer in C++?
我正在处理一段性能要求非常高的代码。我需要执行一些格式化的字符串操作,但我试图避免内存分配,甚至是内部库分配。
在过去,我会做类似于以下内容的操作(假设C++11(:
constexpr int BUFFER_SIZE = 200;
char buffer[BUFFER_SIZE];
int index = 0;
index += snprintf(&buffer[index], BUFFER_SIZE-index, "Part A: %dn", intA);
index += snprintf(&buffer[index], BUFFER_SIZE-index, "Part B: %dn", intB);
// etc.
我更愿意使用所有C++方法(例如 ostringstream(来执行此操作,而不是旧的 C 函数。
我意识到我可以使用 std::string::reserve 和 std::ostringstream 提前获取空间,但这仍然会执行至少一个分配。
有人有什么建议吗?
提前谢谢。
有人有什么建议吗?
是的,使用 std::ostrstream。我知道它已被弃用。但我发现它对于输出到静态缓冲区很有用。如果发生异常,则不可能发生内存泄漏。 根本不分配内存。
#include <strstream> // for std::ostrstream
#include <ostream> // for std::ends
// :
constexpr int BUFFER_SIZE = 200;
char buffer[BUFFER_SIZE];
std::ostrstream osout(buffer, sizeof(buffer));
osout << "Part A: " << intA << "Part B: " << intB << std::ends;
我感谢所有发布建议的人(即使在评论中(。
我很欣赏 SJHowe 的建议,它是解决问题的最简短的解决方案,但我希望通过这次尝试做的一件事是开始为未来的C++编码,而不是使用任何不推荐使用的内容。
我决定采用的解决方案源于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++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- readAll() 或 readAllStandardOutput() 在执行之前也返回一个空字符串
- 如何在没有外部库的情况下使用C++03约束执行基于正则表达式的字符串操作
- 如何在C++中对静态缓冲区执行字符串格式化?
- C++ - 查找函数无法在子字符串上执行
- 如何在 Python 或 C++ 中执行任意字符串?
- 是否有用于执行反向字符串拆分器的开箱即用功能?
- 如何使此函数使用 getline 读取字符串并使用 int 执行相同的行为?
- 如何对字符串作为指针执行大写转换
- 代码问题将字符串转换为图表执行
- QProcess::执行环境变量扩展字符串
- 如何使用 Win32 WCHAR 执行字符串操作
- 在执行字符串时更改字符会使程序崩溃
- 视觉 建议在C++中执行字符串分配什么?
- 我如何在c++中执行字符串作为shell脚本
- 当 boost 的 io 服务正在运行时,无法执行字符串
- 执行字符串分配时,C++程序崩溃