Ownership/delete'ing the facet in a locale (std::locale)

为君一笑 提交于 2019-12-06 17:18:28

问题


I wrote the following function to get a date/time string using boost.date_time.

namespace bpt = boost::posix_time;

string
get_date_time_string(bpt::ptime time)
{
  bpt::time_facet * facet(new bpt::time_facet);
  facet->format("%Y%m%d%H%M%S");

  stringstream return_value;
  return_value.imbue(std::locale(std::locale::classic(), facet));
  return_value << time;

  return return_value.str();
}

I had a quick question about the ownership/delete'ing of the facet object. std::locale's constructor is not explicit on the ownership/delete'ing of the facet. Tried using shared_ptr-wrapped and stack allocated versions of facet - both of which caused seg-faults. Also, running the above function through valgrind didn't show any leaks(which probably implies that the locale or stream is taking care of delete'ing), but I just wanted to be clear that I am doing the right thing here. Thanks.


回答1:


According to Stroustrup, a 0 argument passed to the constructor tells the facet that the locale will handle destruction, and the both constructors of bpt::time_facet default to 0 when it isn't supplied. A non-zero value, though, implies that the programmer must explicitly handle the destruction of the facet.



来源:https://stackoverflow.com/questions/5330459/ownership-deleteing-the-facet-in-a-locale-stdlocale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!