我知道使用 %s
格式说明符和这样的std::string
会导致未定义的行为:
std::string myString = "test";
printf("%s", myString);
但是使用相同的说明符和带有boost::format
的std::string
可以节省吗?
#include <boost/format.hpp>
int main()
{
std::string myString = "test";
boost::format fmt("%s");
fmt % myString;
std::cout << fmt.str();
return 0;
}
%s
指定了一个(常量(char*
,但我提供了一个std::string
。这是否也会导致UB?
将
%s
与 boost::format
和 std::string
一起使用是安全的。与printf
相反,格式字符串中的类型字符"不会将相关参数强加为一组受限制的类型,而只是设置与此类型规范相关联的标志。
http://www.boost.org/doc/libs/1_49_0/libs/format/doc/format.html#printf_directives