【发布时间】:2018-12-30 05:47:27
【问题描述】:
我基本上是在尝试为std::map 创建一个线程安全的包装类。
由于我来自 C,我很难弄清楚 C++ 的所有细微差别。
我正在尝试覆盖[] operator 以获取std::string 参数,以便将其传递给我的std::map 成员。
通过std::map::operator[] 的引用,这应该可以正常工作:
T& operator[]( const Key& key );
这是我的课:
thread_map.hpp
#ifndef THREAD_MAP_H
#define THREAD_MAP_H
#include <map>
#include <functional>
#include <mutex>
template <class T>class Thread_map
{
private:
std::map<std::string, T> map;
std::mutex map_mutex;
public:
~Thread_map();
T& at(size_t pos);
T& operator[](std::string &key);
size_t size() const;
bool empty() const;
void clear();
void insert(std::pair<std::string, T> pair);
T& erase(const std::string &key);
bool for_each(std::function<bool (Thread_map, std::string&, T&)> fun);
};
template<class T> Thread_map<T>::~Thread_map()
{
this->map.clear();
}
template<class T> T& Thread_map<T>::at(size_t pos)
{
T *value;
this->map_mutex.lock();
value = this->map.at(pos);
this->map_mutex.unlock();
return value;
}
template<class T> T& Thread_map<T>::operator[](std::string &key)
{
this->map_mutex.lock();
T &value = this->map[key];
this->map_mutex.unlock();
return value;
}
template<class T> size_t Thread_map<T>::size() const
{
size_t size;
this->map_mutex.lock();
size = this->map.size();
this->map_mutex.unlock();
return size;
}
template<class T> bool Thread_map<T>::empty() const
{
bool empty;
this->map_mutex.lock();
empty = this->map.empty();
this->map_mutex.unlock();
return empty;
}
template<class T> void Thread_map<T>::clear()
{
this->map_mutex.lock();
this->map.clear();
this->map_mutex.unlock();
}
template<class T> void Thread_map<T>::insert(std::pair<std::string, T> pair)
{
this->map_mutex.lock();
this->map.insert(pair);
this->map_mutex.unlock();
}
template<class T> T& Thread_map<T>::erase(const std::string &key)
{
T *value;
this->map_mutex.lock();
value = this->map.erase(key);
this->map_mutex.unlock();
return value;
}
template<class T> bool Thread_map<T>::for_each(std::function<bool
(Thread_map, std::string&, T&)> fun)
{
}
#endif
我把实现放到了头文件中,因为我听说你是用模板类来做的。我是对的吗? 我的问题是,当我尝试打电话给运营商时
Thread_map<std::string> map;
map["mkey"] = "value";
g++ 在 map["mkey"] 上抛出一个无效的初始化错误。
据我了解,问题在于mkey 被编译为std::string("mkey"),这只是值,而不是参考。
但是为什么或如何以下工作呢?
std::map<std::string, std::string> map;
map["mkey"] = "value";
我的意思是我可以按值传递字符串,但这似乎效率低下。
【问题讨论】:
-
比较
T& operator[]( const Key& key )和T& Thread_map<T>::operator[](std::string &key)。前者中存在一个关键字,而后者中缺少一个关键字。提示:以c开头,以t结尾。 -
谢谢忽略了:D
-
您的代码似乎充满了错误。
-
你能告诉我错误是什么或不是Kkid。我对 C++ 有点陌生?好吧,请您参考飞翔的那个链接:*.com/questions/8752837/…
-
@pear 尝试
erase字典中的一个键,使用empty函数,使用size函数(提示-empty和size问题是同一种),并使用at函数。