2015-04-23 28 views
1

對於我的一個項目,我需要使用的shared_ptr到結構TM爲重點,以一個STL地圖。以下是我的測試代碼。在for循環中,有兩種方法可以創建shared_ptr:1)TmSPtr tm_ptr = std :: make_shared(* tminfo); 2)TmSPtr tm_ptr(tminfo)。兩者都可以編譯;在運行時間期間然而,第二方法將引發錯誤:「*錯誤在`./a.out':無():無效指針:0x00007f52e0222de0 *中止(核心轉儲)」,這表明它嘗試釋放存儲器那不存在。我對智能指針還是比較陌生的,所以希望能夠從論壇中獲得一些見解。比需要的,我可能包括多個報C++ STL的地圖,其關鍵是shared_ptr的<struct tm>

道歉

#include <iostream> 
#include <map> 
#include <algorithm> 
#include <iterator> 
#include <memory> 
#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 
#include <unistd.h> 

using namespace std; 

typedef std::shared_ptr<struct tm> TmSPtr; 

int main() 
{ 
    cout << "\nTesting a map where key is a smart ptr to struct tm:\n"; 
    map<TmSPtr, int> price_series; 

    for (int i = 0; i < 5; ++i) { 
     time_t now; 
     time(&now); 
     struct tm * tminfo = localtime(&now); 
     printf("Current local time and date: %s", asctime(tminfo)); 

     TmSPtr tm_ptr = std::make_shared<struct tm>(*tminfo); // TmSPtr tm_ptr(tminfo); would fail in run time 

     price_series.insert(std::pair<TmSPtr, int>(tm_ptr, i)); 

     usleep(1000000); // 1 sec 
    } 
    return 0; 
} 
+1

你爲什麼要使用一個共享的指針作爲你的密鑰,而不是類型本身? – Qartar

+0

我在地圖中使用price_series作爲變量名稱。其實我可以有1000個價格系列,所有這些都有相同的時間戳。我認爲使用struct tm太昂貴了,不是。實際上只有一系列時間戳。希望我的解釋是有道理的。 – tgh123

+0

改爲使用'mktime()'並存儲'time_t'(整數)。使用指針作爲鍵是一個壞主意,使用shared_ptrs作爲鍵是一個可怕的想法。 – Qartar

回答

0

共享指針刪除其對象時,該對象的所有引用超出範圍。這意味着底層對象需要使用new進行分配。但是你的第二個方法是指向一個靜態分配的變量 - 它會自動銷燬。第一種方法創建對象的副本,因此是安全的。

4

localtime(3)說:「返回值指向靜態分配結構......」。這意味着內存不在堆中,因此不應該取消分配。

你的第一種方法的作品,因爲它副本結構。

+0

謝謝。我無法弄清楚爲什麼我可以打印兩行,如「當前的當地時間和日期......」。我以爲我應該只有一條線。 – tgh123