對於我的一個項目,我需要使用的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;
}
你爲什麼要使用一個共享的指針作爲你的密鑰,而不是類型本身? – Qartar
我在地圖中使用price_series作爲變量名稱。其實我可以有1000個價格系列,所有這些都有相同的時間戳。我認爲使用struct tm太昂貴了,不是。實際上只有一系列時間戳。希望我的解釋是有道理的。 – tgh123
改爲使用'mktime()'並存儲'time_t'(整數)。使用指針作爲鍵是一個壞主意,使用shared_ptrs作爲鍵是一個可怕的想法。 – Qartar