[Effective-cpp] Item 2: The String Formatters of Manor Farm, Part 1: sprintf

Gregory Haley ghaley at venaca.com
Thu Oct 28 15:50:00 EDT 2004


> Manor Farm,Part 1: sprintf
> 
> Item 2: The String Formatters of Manor Farm, Part 1: sprintf
> 
> The advantages and disadvantages of sprintf are discussed. 
> The alternatives to using sprintf will be discussed in Item 
> 3, the following item. Those alternatives are: snprintf, 
> std::stringstream, std::strstream, and boost::lexical_cast.
> 
> The advantages of sprintf are:
> 
> It's part of the C++ standard.
> 
> It's easy to use, and the resulting code is clear.
> 
> It's highly efficient, since it writes directly to a character array.

At the risk of having abuse and ridicule rain down on my head, I have to
confess, I've never gotten sprintf to work for me right out of the box.  I'm
sure this has more to do with the route I took to c++, which involved only a
smattering of c here and there, but I don't agree that it's either easy to
use or produces clear code.  Ironically, it is not until reading this that I
finally understood as well as I could this tool.

Possibly, if I had been writting in C for years and years, I might find that
the string formatters in the next item look ugly and non-intuitive.  Since
I'm responsible for the review of Item 3, I'll stop here.

Once you work out the logic, it is very efficient.

> The disadvantages are:
> 
> There is no length safety. There is no way to explicitly 
> limit how much of the character array is used. This can and 
> often does result in buffer overrun errors.
>
> There is no type safety. Errors in the format specification 
> are not caught at compile time. They're caught at run time, 
> if you're lucky. 
> Lint tools will catch many of these problems.
> 
> It is difficult to use in a template. An ugly example using 
> specializations is provided.

In his Item summary, Herb indicates "No" for usable in a Template.  Indeed,
I would say, the only way to use this in a "Template" context is to write a
Template for each and every kind of input that you can hopefully remember,
and then it seems this really violates the spirit of templates.

Ultimately, I think it's drawbacks far outweigh the advantages.
 
> For those wondering about "Manor Farm": in the novel "Animal 
> Farm", the original name of the farm that became "Animal 
> farm" was "Manor Farm".

Thanks for the literature reminder.  I had forgotten that detail.

ciao!
greg.

Gregory Haley

---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.779 / Virus Database: 526 - Release Date: 10/19/2004
 




More information about the Effective-cpp mailing list