Pointer to a value in std :: map

I have std :: map, which is used by several threads to store data. The card is declared as follows:

std::map<int, Call> calls;

From each thread I have to get a mutex lock, get a pointer or a link to an object belonging to this thread, then release the mutex lock. I can change the object after that, because each object is used by only one thread. As soon as the thread dies, the corresponding pair on the card will also be deleted.

I would like to know a better way to implement this. I thought of two ways:

1) I know it might look awfully crazy, but still

std::map<int, Call> calls;
...

{
    mutex.lock();
    Call* callptr = &calls[id];
    mutex.unlock();

   // use callptr
}

or 2) I think this one looks more reasonable

std::map<int, std::auto_ptr<Call> > calls;

...

{
    mutex.lock();
    std::auto_ptr<Call> callptr = map[id];
    mutex.unlock();

    // use callptr

    mutex.lock();
    map[id] = callptr;
    mutex.unlock();
}

dll, . DLL, , DLL . std:: map, - , .

+3
3

:

mutex.lock();

std::map<int, Call>::iterator callptr = calls.find(id);
callptr->second.foo();
...

mutex.unlock();

, - , , .

, std::auto_ptr mapped_type of std::map - , operator= . , , .

+5

" " - .

, , Thread Local Storage .

+3

Do not use auto_ptr in STL containers. DO NOT. Developers really need to try and make a compilation error there. Standard containers tend to copy things around. This is very wrong with auto_ptr.

+2
source

Source: https://habr.com/ru/post/1712744/


All Articles