-1

So i got the variable

std::map<std::string, std::shared_ptr<MyClass>> m_map;

During the program shutdown routine, I'd like to exploit the wonderful smart pointer property which should (if I'm not wrong) take care of the destruction of MyClass instances, once their own last reference is destroyed.

So I'm just calling m_map.clear(), but this

  1. SOMETIME produces the aforementioned

    corrupted double-linked list
    
  2. while in other cases (unknown thus uncontrolled variable) works correctly,

  3. and finally in other cases (controlled variable; in facts, different program configuration) produces

    terminate called after throwing an instance of 'std::runtime_error*'
    

I'd gladly receive at least some hint on approaches to the problem. Since the program is strongly multithreaded (and I know very little of it) I'm wondering if the deletion of that pointer to MyClass instance would interfere with something else.

Community
  • 1
  • 1
Patrizio Bertoni
  • 2,582
  • 31
  • 43
  • 2
    Have you tried using valgrind or gdb to analyze your code? – NathanOliver Jun 23 '15 at 11:48
  • 1
    We cannot know what the issue is without seeing your "sometime", "other cases" and "other cases". – Cory Kramer Jun 23 '15 at 11:48
  • 2
    You should not see the new smart pointers as just auto-deleting pointers, but instead in an ownership perspective. Can a resource have only one owner at a time? Then use `std::unique_ptr`. Can a resource have multiple simultaneous owners? Then use `std::shared_ptr`. – Some programmer dude Jun 23 '15 at 11:50
  • A Basic but important question: As you wrote it is multithreaded; so you are doing synchronization, right? – Thomas Sparber Jun 23 '15 at 11:51

1 Answers1

1

This type of error is caused when you're calling at least 2 methods that affect the structure from at least 2 different threads.

For example, calling clear() on std::map will change the structure of the map itself (remove all items). And if you have another thread that's using that map at the same time (IE. looping over it, inserting, etc.) then you'll have the exception you're seeing.
The exception is caused because the std::map structure is in an invalid state (map nodes are in the middle of changing positions) while you're trying to access it.

The simplest solution would be to hold a lock whenever you access that map object.

Yochai Timmer
  • 48,127
  • 24
  • 147
  • 185