2013-07-22 110 views
23

我有一個函數使用Boost.DateTime庫來生成當前的GMT/UTC日期和時間字符串(live example)。誰負責刪除方面?

std::string get_curr_date() { 
    auto date = boost::date_time::second_clock<boost::posix_time::ptime>::universal_time(); 

    boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%a, %d %b %Y %H:%M:%S GMT"); 

    std::ostringstream os; 
    os.imbue(std::locale(os.getloc(), facet)); 
    os << date; 

    return os.str(); 
} 

這主要是基於Boost.DateTime's example

//example to customize output to be "LongWeekday LongMonthname day, year" 
//         "%A %b %d, %Y" 
date d(2005,Jun,25); 
date_facet* facet(new date_facet("%A %B %d, %Y")); 
std::cout.imbue(std::locale(std::cout.getloc(), facet)); 
std::cout << d << std::endl; 
// "Saturday June 25, 2005" 

我的代碼工作很好,但我現在因爲含有new這些特定的行感到惶恐:

  • boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%a, %d %b %Y %H:%M:%S GMT");

  • date_facet* facet(new date_facet("%A %B %d, %Y"));

正如你所看到的,有中沒有delete Boost.DateTime的,所以我莫名其妙地推測,當務之急是爲我deletedate_facet。我用std::unique_ptr來包裝new ed time_facet對象。

std::unique_ptr<boost::posix_time::time_facet> facet(new boost::posix_time::time_facet("%a, %d %b %Y %H:%M:%S GMT")); 

但是,我得到段錯誤,您可以在here中看到。我也試過手動編輯new ed指針,並且仍然得到相同的錯誤(抱歉,無法在Coliru中重現錯誤)。

time_facet指針在構造std::locale對象時作爲參數傳遞,所以我很困惑誰負責delete這個方面。

因此,這裏是我的問題的核心:

  • 我必須對deletetime_facet或者是std::locale對象負責delete荷蘭國際集團呢?

請注意,boost::posix_time::time_facetboost::date_time::date_facet這,反過來,從std::locale::facet得出的。這個問題可能概括爲std::locale::facet,雖然我的問題是特定於time_facet

這裏是std::locale的構造一些文檔:

回答

24

我需要刪除time_facet還是std :: locale對象 負責刪除它嗎?

你不需要從std::locale::facet刪除time_facet只要time_facet派生,它應該。 std::locale::facet是一個基類,所有方面都應該從實現一種引用計數的形式中派生出來。標準這樣說:

§22.3.1.6

一旦小面參考是從一個區域設置對象通過調用 use_facet<>得到,該參考文獻仍然可用,並且從它 成員函數的結果可以是緩存和重用,只要某些 區域設置對象引用該方面。

一旦方面的所有引用不被使用,如果它的引用計數爲0

這在§22.3.1.1所有指定的std::locale的析構函數將管理和刪除的小引用。 2在C++ 11標準中。它的地址如下:

構造函數的refs參數用於生存期管理。

- 對於refs == 0,實施執行delete static_cast<locale::facet*>(f)(其中,f是一個指針刻面) 當包含小面的最後的區域設置對象被銷燬;對於 refs == 1,實現從不破壞方面。

2

的語言環境是負責刪除方面。

+0

這意味着locale不能被聲明爲'const static'嗎? – agodinhost

5

不回答你的問題,因爲其他人已經做到了。但是,實際上並不需要每次構建語言環境。

std::string get_curr_date_time() { 
    namespace bpt = boost::posix_time; 
    namespace bdt = boost::date_time; 
    std::ostringstream os; 
    auto date = bdt::second_clock<bpt::ptime>::universal_time(); 
    const static std::locale currlocale (os.getloc(), new bpt::time_facet("%Y%m%d%H%M%S")); 
    boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%a, %d %b %Y %H:%M:%S GMT"); 

    os.imbue(currlocale); 
    os << date; 
    return os.str(); 
}