对于我的一个项目,我需要使用的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