boost::format vs sprintf

2019-07-20 05:32发布

问题:

Which one is better: boost::format or sprintf? I also want to know which one is more type safe to use.

I know one limitation with sprintf that it formats a char[] object, and the size of char[] should be sufficient to hold the formatted string. But does boost::format also hold the same limitation or not. can Anyone point out me a doc on net which I would refer for the difference among boost::format and sprintf.

回答1:

In terms of robustness and type-safety boost::format is a clear winner. It doesn't have an issue with buffer size as it uses a dynamic stream. The types of the parameters are retained in the function call, thus the formatter can intelligently convert. This also means there is no problem of screwing up the stack with mismatched types. Type conversion is also available in this model.

The drawbacks of format are its speed and that it is a bit cumbersome. Its speed is quite a bit lower than that of sprintf for formats that sprintf can handle. Its syntax is also a bit more involved than a quick call to sprintf.

For simple token formatting I usually use sprintf. For complex string formatting I tend to use boost format, or iostreams.



回答2:

sprintf() is not type-safe; therefore boost::format will be more type-safe. sprintf() is prone to buffer overflow; you'd be better off using snprintf() than sprintf(), but you're very likely to be better off still with boost::format.



回答3:

It depends on how you define "better".

printf is quite fast and readily available being a part of standard library. However it has safety issues that are to some extent addressed with __attribute__ ((format (printf, ...)) in GCC.

Boost Format is safe, but it is much slower and, as pointed out by @edA-qa mort-ora-y, somewhat cumbersome to use due to unconventional use of operator%.

If you want the best of both world, the convenient function-call formatting API and speed of printf, and safety of Boost Format, consider the {fmt} library. It supports both printf and Python's str.format syntax:

fmt::print("Hello, {}!", "world");  // uses Python-like format string syntax
fmt::printf("Hello, %s!", "world"); // uses printf format string syntax

Disclaimer: I'm the author of {fmt}



标签: c++ boost