2015-04-23 21 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