std :: map中的值的指针 [英] Pointer to Value in a std::map

查看:412
本文介绍了std :: map中的值的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个std :: map,被多个线程用来存储数据。地图的声明如下:

I have a std::map that is used by multiple threads to store data. The map is declared like this:

std::map<int, Call> calls;

从每个线程,我必须获取一个互斥锁,获取一个指针或引用对象属性到那个线程,然后释放互斥锁。我之后可以修改对象,因为每个对象只由一个线程使用。一旦线程死亡,映射中的相应对也将被删除。

From each thread, I have to acquire a mutex lock, obtain a pointer or reference to the object belonging to that thread, then release the mutex lock. I can modify the object after that because each object is used only by one thread. As soon as the thread dies, the corresponding pair in the map would also get deleted.

我想知道实现这个的最好方法。我在想两种方式:

I would like to know the best way to implement this. I was thinking of two ways:

1)我知道这个可以看起来疯狂,但仍然

1) I know this one could look outrageously crazy, but still

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

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

   // use callptr
}

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实现,但任何人都可以告诉我,如果这些方法之一是确定,或有办法使它更稳定。

The threads actually are created in a different dll and I don't have the code for that. This dll that I'm writing now gets imported by that dll and used. So it has to be implemented with std::map only, but could anyone tell me if one of these methods is ok or if there are ways to make it more stable.

谢谢

推荐答案

您应该使用迭代器:

mutex.lock();

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

mutex.unlock();

您的第一个指针解决方案是有问题的,因为地图中对象的生命周期是不确定的

Your first solution with pointers is problematic, because the lifetime of the object in the map is uncertain - it may be moved when the tree is rebalanced when elements are inserted or deleted.

您的第二个解决方案根本不会工作,因为 std :: auto_ptr 不符合 std :: map mapped_type 的要求 - 主要是因为复制构造函数和 operator = 不实际复制。你可能不会得到编译器错误,但是你会在运行时得到非常奇怪的行为。

Your second solution won't work at all, because std::auto_ptr does not fulfil the requirements for mapped_type of std::map - mostly because its copy constructor and operator= don't actually copy. You likely won't get a compiler error, but you'll get very weird behavior at run-time.

这篇关于std :: map中的值的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆