以下程序正常工作:
#include <iostream>
#include <boost/lexical_cast.hpp>
int main(int argc, const char *argv[])
{
std::string to_port("8004");
unsigned short intport = boost::lexical_cast<unsigned short>(to_port);
std::cout << intport << std::endl;
std::cout << std::hex << intport << std::endl;
return 0;
}
但是如果我们将第一行修改main
成:
std::string to_port;
我们得到了异常:
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::bad_lexical_cast> >'
what(): bad lexical cast: source type value could not be interpreted as target
Aborted (core dumped)
这导致您传递给lexical_cast
.
您可以打印to_port
变量以在 ? 之前验证其内容lexical_cast
?您确定它已正确初始化并且在使用时仍在范围内(例如,不涉及临时对象,没有悬空指针)?