Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;STL映射,其密钥为共享\u ptr<;结构tm>;_C++_Dictionary_Shared Ptr - Fatal编程技术网

C++ C++;STL映射,其密钥为共享\u ptr<;结构tm>;

C++ C++;STL映射,其密钥为共享\u ptr<;结构tm>;,c++,dictionary,shared-ptr,C++,Dictionary,Shared Ptr,对于我的一个项目,我需要使用shared_ptr to struct tm作为STL映射的键。下面是我的测试代码。在for循环中,有两种方法可以创建共享的_ptr:1)TmSPtr tm_ptr=std::make_shared(*tminfo);2) TmSPtr tm_ptr(tminfo)。两者都可以编译;但是,在运行时,第二个方法会抛出一个错误:“`./a.out':free():无效指针:0x00007f52e0222de0*中止(内核转储)”,表示它试图释放不存在的内存。我对智能指针

对于我的一个项目,我需要使用shared_ptr to struct tm作为STL映射的键。下面是我的测试代码。在for循环中,有两种方法可以创建共享的_ptr:1)TmSPtr tm_ptr=std::make_shared(*tminfo);2) TmSPtr tm_ptr(tminfo)。两者都可以编译;但是,在运行时,第二个方法会抛出一个错误:“`./a.out':free():无效指针:0x00007f52e0222de0*中止(内核转储)”,表示它试图释放不存在的内存。我对智能指针还很陌生,所以希望能从论坛上获得一些见解

抱歉,我可能包含了比需要更多的标题

#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;
}
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
typedef std::共享_ptr TmSPtr;
int main()
{

当对对象的所有引用都超出范围时,共享指针不能删除它们的对象。这意味着需要使用
new
分配基础对象。但是第二个方法指向静态分配的变量,该变量会自动销毁。第一个方法创建对象的副本,因此是安全的。

当对对象的所有引用超出范围时,共享指针将删除其对象。这意味着需要使用
new
分配基础对象。但第二个方法指向静态分配的变量,该变量会自动销毁。第一个方法创建对象的副本,因此是安全的。

说明:“返回值指向静态分配的结构…”。这意味着内存不在堆上,因此不应取消分配

第一个方法之所以有效,是因为它复制了结构。

说:“返回值指向静态分配的结构…”。这意味着内存不在堆上,因此不应取消分配


您的第一个方法之所以有效,是因为它复制了结构。

为什么要使用共享指针作为键而不是类型本身?我在映射中使用price_系列作为变量名。实际上,我可以有1000个price系列,所有这些系列都共享相同的时间戳。我认为使用struct tm太贵了,不是吗?实际上只有1个系列时间戳。希望我的解释有意义。使用
mktime()
并存储
time\t
(整数)相反。使用指针作为键是一个坏主意,使用共享指针作为键是一个糟糕的主意。为什么要使用共享指针作为键而不是类型本身?我在映射中使用price_系列作为变量名。实际上,我可以有1000个price系列,所有这些系列共享相同的时间戳。我认为使用struct tm太贵了,不是吗re实际上只是一系列时间戳。希望我的解释有意义。使用
mktime()
并存储一个
time\t
(整数)。使用指针作为键是一个坏主意,使用共享的ptr作为键是一个糟糕的主意。谢谢。我不明白为什么我可以像这样打印两行“当前本地时间和日期…”。我想我应该只有一行。谢谢。我不明白为什么我可以打印出两行,如“当前本地时间和日期…”。我想我应该只有一行。