dictionary - C++ STL map, whose key is shared_ptr<struct tm> -


for 1 of projects, need use shared_ptr struct tm key stl map. below testing code. in loop, there 2 ways create shared_ptr: 1) tmsptr tm_ptr = std::make_shared(* tminfo); 2) tmsptr tm_ptr(tminfo). both can compile; during run-time, 2nd method throws error: "* error in `./a.out': free(): invalid pointer: 0x00007f52e0222de0 * aborted (core dumped)", indicating tries free memory not exist. still quite new smart pointers, can insight forum.

apologies may have included more headers needed

#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 map key smart ptr struct tm:\n";     map<tmsptr, int> price_series;      (int = 0; < 5; ++i) {         time_t now;         time(&now);         struct tm * tminfo = localtime(&now);         printf("current local time , date: %s", asctime(tminfo));          tmsptr tm_ptr = std::make_shared<struct tm>(*tminfo); // tmsptr tm_ptr(tminfo); fail in run time          price_series.insert(std::pair<tmsptr, int>(tm_ptr, i));          usleep(1000000); // 1 sec     }     return 0; } 

localtime(3) says: "the return value points statically allocated struct ...". means memory not on heap, should not de-allocated.

your first method works because copies structure.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -