【问题标题】:Converting std::string to boost::posix_time::ptime将 std::string 转换为 boost::posix_time::ptime
【发布时间】:2012-05-24 06:50:00
【问题描述】:

以下代码将std::string 转换为boost::posix_time::ptime

在分析之后,我发现花在该函数上的大部分时间(大约 90%)都浪费在为 time_input_facet 分配内存上。我不得不承认我不完全理解下面的代码,特别是为什么time_input_facet 必须分配在空闲内存上。

using boost::posix_time;

const ptime StringToPtime(const string &zeitstempel, const string &formatstring)
{
    stringstream ss;
    time_input_facet* input_facet = new time_input_facet();
    ss.imbue(locale(ss.getloc(), input_facet));
    input_facet->format(formatstring.c_str());

    ss.str(zeitstempel);
    ptime timestamp;

    ss >> timestamp;
    return timestamp;
}

你有什么办法可以摆脱分配吗?

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    在函数内部将 input_facet 设为静态:

    static time_input_facet *input_facet = new time_input_facet();
    

    这将仅在第一次函数调用时构造构面,并将重用该构面。我相信 facet 允许对同一个对象进行多次后续调用。

    更新:您也不需要同时构建字符串流和语言环境。只需在单独的函数中或在静态初始化中执行一次,然后使用流。

    更新2:

    const ptime StringToPtime(const string &zeitstempel, const string &formatstring)
    {
      static stringstream ss;
      static time_input_facet *input_facet = NULL;
      if (!input_facet)
      {
        input_facet = new time_input_facet(1);
        ss.imbue(locale(locale(), input_facet));
      }
    
      input_facet->format(formatstring.c_str());
    
      ss.str(zeitstempel);
      ptime timestamp;
    
      ss >> timestamp;
      ss.clear();
      return timestamp;
    }
    

    【讨论】:

    • 我不明白谁为time_input_facet 打电话给delete?我可以使用相同的time_input_facet 进行许多不同格式字符串的转换吗?
    • std::locale 为您调用删除。
    • 是的,input_facet 永远不会被破坏(仅在程序退出时)。如果通过删除冗余分配将性能提高 90%,这是一个很小的代价。当然,你可以把它设为静态全局或类成员,这样它就会被正确地销毁。
    • 为了防止delete被调用,你必须将一个非零数传递给构造函数(see here)。例如,time_input_facet input_facet(1);
    • @VladimirSinenko:如果我在我的函数中将 input_facet 作为静态变量,根据 Jesse 的说法,临时创建的 locale 对象将在第一次函数调用后调用 delete。所以我会有一个悬空指针,但它不起作用?如果我将您的答案和 Jesses 评论结合起来,我应该在 time_input_fact 的构造函数中使用静态变量和非零数字。你同意吗?
    猜你喜欢
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多