Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using %s format specifier with boost::format and std::string

I know that using the %s format specifier and std::string like this leads to undefined behaviour:

std::string myString = "test";
printf("%s", myString);

But is it save to use the same specifier and a std::string with boost::format?

#include <boost/format.hpp>

int main() 
{
   std::string myString = "test";

   boost::format fmt("%s");
   fmt % myString;

   std::cout << fmt.str();

   return 0;
}

%s specifies a (const) char*, but I provide a std::string. Could this lead to UB too?

like image 678
Ronald McBean Avatar asked May 20 '12 08:05

Ronald McBean


People also ask

What is boost format?

The format library provides a class for formatting arguments according to a format-string, as does printf, but with two major differences : format sends the arguments to an internal stream, and so is entirely type-safe and naturally supports all user-defined types.

What is %p format string?

%p expects the argument to be of type (void *) and prints out the address. Whereas %x converts an unsigned int to unsigned hexadecimal and prints out the result.


1 Answers

It is safe to use %s with boost::format and std::string. In contrast to printf, the type character in the format string "does not impose the concerned arguments to be of a restricted set of types, but merely sets the flags that are associated with this type specification."

http://www.boost.org/doc/libs/1_49_0/libs/format/doc/format.html#printf_directives

like image 189
nosid Avatar answered Sep 27 '22 18:09

nosid