【发布时间】:2016-11-14 22:14:43
【问题描述】:
我正在尝试找出一种跨多个文件共享数据的好方法,但我确信有些方法比其他方法更好,所以我来这里询问在此共享数据的最安全方法是什么方式。在下面的示例中,我将展示到目前为止我是如何做到的,但我觉得这并不是最好的方法。
举个例子,我有 5 个文件:file1.h、file1.cpp、file2.h、file2.cpp 和 main.cpp。它们可能看起来像这样:
//main.cpp
#include "file1.h"
#include "file2.h"
int main(){
PushOne pushOne;
PushTwo pushTwo;
pushOne.Push();
pushTwo.Push();
for (int i =0; i<q.size(); i++){
std::cout << q.front() << std::endl;
q.pop();
}
return 0;
}
//file1.h
namespace Foo{
extern std::queue<int> q; //resource to be shared across files
class PushOne{
public:
void Push();
};
}
//file1.cpp
#include "file1.h"
namespace Foo{
std::queue<int> q;
void PushOne::Push(){
q.push(1);
}
}
//file2.h
#include "file1.h" //#include this to have access to namespace variables declared in this file...Seems sort of inefficient
namespace Foo{
class PushTwo{
public:
void Push();
};
}
//file2.cpp
#include "file2.h"
namespace Foo{
void PushTwo::Push(){
q.push(2);
}
}
所以在这里,我有一个命名空间变量 std::queue q,我想在 file1 和 file2 中访问它。我应该将这个命名空间变量放入两个文件之一,而只需 #include 另一个文件,这似乎没有任何意义。有没有更好的方法来做到这一点?这似乎授予对std::queue<int> q 的某种“不对称”访问权限。我什至不知道这是否一定是负面的事情,但也许有人可以阐明这种方法的效率或提出另一种方法。
【问题讨论】:
-
全局可变数据看起来不是一个好主意。看一下关于 SE 的一些解释:stackoverflow.com/questions/484635/are-global-variables-bad,programmers.stackexchange.com/questions/148108/…。命名空间不会降低全局数据的全局性。
-
如果你真的想要全局数据,可以考虑单例(反)模式:en.wikipedia.org/wiki/Singleton_pattern
-
在遵循所有这些建议后,您可以而且应该使用lock 来确保您的队列是线程安全的。
标签: c++ scope namespaces include