C++ 将std::string转换为boost::posix_time::ptime

C++ 将std::string转换为boost::posix_time::ptime,c++,boost,C++,Boost,以下代码将std::string转换为boost::posix_time::ptime 在分析之后,我发现在该函数中花费的大部分时间(大约90%)都浪费在了time\u input\u方面的内存分配上。我必须承认,我不完全理解以下代码,特别是为什么必须在空闲内存上分配时间输入方面 using boost::posix_time; const ptime StringToPtime(const string &zeitstempel, const string &formatst

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

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

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;
}

您认为有什么方法可以摆脱分配吗?在函数中使输入方面保持静态:

static time_input_facet *input_facet = new time_input_facet();
这将仅在第一次函数调用时构造facet,并将重用facet。我相信facet允许对同一对象进行多个后续调用

更新:您也不需要同时构造stringstream和locale。只需在单独的函数中或在静态初始化中执行一次,然后使用流

更新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;
}

我不明白是谁调用
delete
来获取
time\u input\u facet
?我可以使用相同的
time\u input\u facet
进行许多不同格式字符串的转换吗?为您调用delete。是的,输入方面永远不会被破坏(仅在程序退出时)。如果通过删除冗余分配将性能提高90%,那么这是一个很小的代价。当然,您可以将其设置为静态全局或类成员,以便正确地对其进行销毁。要防止调用
delete
,必须将非零数字传递给构造函数()。例如,
time\u input\u facet input\u facet(1)
@vladimirsinko:根据Jesse的说法,如果我在我的函数中将输入作为静态变量,那么临时创建的
locale
对象将在第一次函数调用后调用delete。所以我会有一个悬空的指针,它不会工作?如果我把你的答案和Jesses的评论结合起来,我应该在time_input_事实的构造函数中使用一个静态变量和一个非零数。你同意吗?