【问题标题】:Using %s format specifier with boost::format and std::string将 %s 格式说明符与 boost::format 和 std::string 一起使用
【发布时间】:2012-05-20 08:37:41
【问题描述】:

我知道像这样使用 %s 格式说明符和 std::string 会导致未定义的行为:

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

但是使用相同的说明符和std::stringboost::format 是否节省?

#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吗?

【问题讨论】:

  • 我可能没抓住重点,但为什么不通过 std::string.c_str()?
  • 因为我在一些遗留代码中发现了很多这样的调用,我正在尝试决定是否需要修复它。另外我想知道将来如何正确使用 %s 说明符。

标签: c++ boost boost-format


【解决方案1】:

%sboost::formatstd::string 一起使用是安全的。与printf 相比,格式字符串中的类型字符“不会将相关参数强制为一组受限制的类型,而只是设置与此类型规范相关联的标志。”

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 2011-04-11
    • 2011-12-28
    • 1970-01-01
    相关资源
    最近更新 更多