我正在使用 QT 编写一个 C++ 应用程序,重点是速度优化。 我想要一些全局对象,对不同线程具有只读访问权限。 在打开线程之前,我必须初始化全局对象并用数据填充它们。
如何保护我的全局对象的集合函数,但仍然可以从主函数访问?
现在的示例代码:
我的类.h
class MyObjectClass {
public:
void SetSome(const QList<QString> &value);
QList<QString> GetSome() const;
private:
QList<QString> m_myMember;
};
主要.cpp
#include "global.h" // some like: extern MyObjectClass g_InihalizedInMain;
#include "anyThread.h"
int main(){
g_InitializedInMain.SetSome() // This Shut work
MyThread thread;
thread.start();
//..
return 0;
}
任意线程.cpp:
#include "global.h"
void thread::run()
{
MyObjectClass newObject = g_InihalizedInMain; //This shut work
g_InitializedInMain.GetSome(); //This shut work
g_InitializedInMain.SetSome(); //This shut not work and give me an error during compile time
newObject.SetSome(); //This shut work
}
如果你能给我一些设计想法,我会很高兴,非常感谢!
最佳答案
class MyPrivateObjectClass : private MyObjectClass
{
public:
friend void main();
};
extern MyPrivateObjectClass g_InitializedInMain;
关于c++ - 多线程设计,C++保护全局成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13143327/