2

看下面的代码,调试和显示转换在 iPhone 模拟器和设备(4S)上都是成功的,但我想知道它是如何工作的?请参阅http://www.cplusplus.com/reference/iostream/ostream/operator%3C%3C/,boost::int64_t 没有重载功能。

如果我使用这个函数来转换任意 boost::int64_t 类型有什么风险吗?提前致谢。

std::stringstream mySS;
boost::int64_t large = 4294967296889977;
mySS<<large;
std::string str = mySS.str(); 
4

1 回答 1

2

它起作用的原因是它boost:int64_t实际上是内置类型的typedef(通常std::int64_t定义在cstdint或类似的东西),所以它可能最终与long long(或相似,取决于平台)相同。当然,有一个超载的stringstream::operator<<

确切的定义,最好参见boost/cstdint.hpp(1.51 版本)。

假设这通常适用于所有主要平台,这可能是一个相对安全的选择。但我怀疑任何人都能够为此提供保证。

如果您使用的目的std::stringstream是在整数和字符串之间进行转换,那么您可以做的最安全的事情就是使用 Boost 自己的转换方式:boost::lexical_cast(1.51 版本)。这是如何完成的:

#include <iostream>
#include <boost/cstdint.hpp>
#include <boost/lexical_cast.hpp>

int main()
{
  boost::int64_t i = 12;
  std::string    s = boost::lexical_cast<std::string>(i);

  std::cout << s << std::endl;
  return 0;
}
于 2012-10-30T03:40:48.477 回答