1

我有一个包含端口的字符串,当我尝试创建一个 tcp 端点时,我需要它的无符号短值

  std::string to_port;
    ....
    boost::lexical_cast<unsigned short>(to_port));

抛出异常 bad lexical cast: source type value could not be interpreted as target

4

1 回答 1

5

以下程序正常工作:

#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?您确定它已正确初始化并且在使用时仍在范围内(例如,不涉及临时对象,没有悬空指针)?

于 2013-05-25T16:12:55.830 回答