我有一个包含端口的字符串,当我尝试创建一个tcp端点时,我需要在unsigned short中使用它的值
std::string to_port;
....
boost::lexical_cast<unsigned short>(to_port));
Run Code Online (Sandbox Code Playgroud)
抛出一个例外 bad lexical cast: source type value could not be interpreted as target
以下程序正常工作:
#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;
}
Run Code Online (Sandbox Code Playgroud)
但是如果我们修改第一行main:
std::string to_port;
Run Code Online (Sandbox Code Playgroud)
我们得到例外:
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)
Run Code Online (Sandbox Code Playgroud)
这导致结论是你传递给的参数有问题lexical_cast.
你可以打印to_port变量来验证它的内容lexical_cast吗?你确定它被正确初始化并且在使用时仍然在范围内(例如,没有临时参与,没有悬空指针)?