ext*_*iam 7 c++ static-initialization c++11
我想知道是否可以确保只在程序的静态初始化步骤中调用函数?
举个例子,假设我有一些包含一个std::map对象的单例类,并公开它的方法insert和at方法.我想确保从它(该at方法)读取数据是线程安全的,据我的理解,这需要确保没有任何东西正在修改数据(即使用该insert方法).
该映射仅在静态初始化期间填充,此时我假设只有一个线程.有什么方法可以确保insert一旦main()开始没有误导用户呼叫?
示例代码
#include <map>
#include <string>
class Singleton {
private:
std::map<std::string, std::string> m_map;
public:
static Singleton& instance() {
static Singleton theSingleton;
return theSingleton;
}
static bool insert(const std::string& key, const std::string& value) {
return instance().m_map.insert(std::make_pair(key, value) ).second;
}
static std::string at(const std::string& key) {
return instance().m_map.at(key);
}
};
static bool inserted = Singleton::insert("Hello", "World"); // fine
bool addItem(const std::string& key, const std::string& value) {
return Singleton::insert(key, value); // not OK
}
Run Code Online (Sandbox Code Playgroud)
不用(?)说实际代码比这个简单的例子更复杂.
在解决方案之后编辑:看起来使尽可能安全的最佳方法是维护一个status变量,记录单例是处于"插入"还是"读取"模式并相应地采取行动.感谢所有人的意见和建议!
小智 4
我想您还想在设置应用程序时使用“at”方法。为什么不添加一个“锁定”方法并像主函数中的第一个函数一样简单地调用它?
#include <map>
#include <string>
class Singleton {
private:
std::map<std::string, std::string> m_map;
bool m_locked;
Singleton() : m_locked(false) { }
public:
static Singleton& instance() {
static Singleton theSingleton;
return theSingleton;
}
static void lock() {
instance().m_locked = true;
}
static bool insert(const std::string& key, const std::string& value) {
if (instance().m_locked) { return false; }
return instance().m_map.insert(std::make_pair(key, value)).second;
}
static std::string at(const std::string& key) {
return instance().m_map.at(key);
}
};
static bool inserted = Singleton::insert("Hello", "World"); // fine
bool addItem(const std::string& key, const std::string& value) {
return Singleton::insert(key, value); // not OK
}
int main(int argc, char** argv)
{
Singleton::lock();
Singleton::insert("Hello2", "World2"); // fails
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
280 次 |
| 最近记录: |