【发布时间】:2016-05-20 10:20:53
【问题描述】:
class log_String {
//These are private!
std::vector<std::string> list;
std::mutex m;
log_String& operator=(const log_String &source); //Operatore assegnazione
log_String(const log_String &source);
public:
log_String() {}; // <---- is this thread_safe?
void add(std::string string) {
std::lock_guard<std::mutex> l(m);
list.push_back(string);
}
void printFile(std::string file) {
std::lock_guard<std::mutex> l(m);
std::ofstream myfile;
myfile.open(file);
for (auto iterator = list.begin(); iterator != list.end(); ++iterator) {
myfile << *iterator << "\n";
}
}
};
log_String() {} 线程安全吗?
我认为即使许多线程同时调用log_String() {} 这应该不是问题吗?我弄错了吗?
如果我错了,可能的解决方案可能是定义它private 并保护获取新锁的新对象的实例化?
【问题讨论】:
-
这个问题没有意义。构造函数在对象的生命周期开始之前 运行。一个不存在的对象如何同时被多个线程访问?
-
@KerrekSB 您的评论应该是一个答案!作为旁注:我问了一个关于对象生命周期是如何开始的问题(stackoverflow.com/questions/20409500/…)并得到了一些有趣的答案。标准中的“初始化完成”是什么意思? :)
-
@GeorgeAl:什么?如何?什么时候?
-
@mantler:表示第一个构造函数已经返回。
-
@KerrekSB,仅供参考stackoverflow.com/a/10586040/6271671
标签: c++ multithreading default-constructor