我正在尝试找出一种跨多个文件共享数据的好方法,但我确信有些方法比其他方法更好,所以我来这里是想问一下在这个过程中共享数据最安全的方法是什么方式。在下面的示例中,我将展示到目前为止我是如何做到的,但我觉得这并不是最好的方法。
让我们举个例子,我有 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 中访问它。我必须将这个 namespace 变量放入两个文件之一,而只是 #include 另一个文件,这似乎没有意义。有没有更好的方法来做到这一点?这似乎授予了对 std::queue<int> q
的某种“不对称”访问权限。 .我什至不知道这是否一定是负面的,但也许有人可以阐明这种方法的效率或提出另一种方法。
最佳答案
如果你真的想这样做,在头文件中定义一个带有静态元素的结构:
MyQueue.h:
struct MyQueue {
static std::queue<int> q;
}
您还必须在相应的 .cpp 文件中定义变量。
MyQueue.cpp:
#inclue "MyQueue.h"
static std::queue<int> MyQueue::q;
您可以通过包含该 header 的任何文件访问它,例如:
MyQueue::q.push(2);
我仍然不推荐这样做,尤其是在有多个线程的情况下,因为它是一个全局变量。
另一种选择是使用单例,但这有同样的问题。
关于C++ 跨文件共享变量的良好做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38332799/