【问题标题】:C++ Good Practices to Share Variables Across Files?跨文件共享变量的 C++ 良好实践?
【发布时间】: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&lt;int&gt; q 的某种“不对称”访问权限。我什至不知道这是否一定是负面的事情,但也许有人可以阐明这种方法的效率或提出另一种方法。

【问题讨论】:

标签: c++ scope namespaces include


【解决方案1】:

如果你真的想这样做,在头文件中定义一个带有静态元素的结构:

MyQueue.h:

struct MyQueue {
   static std::queue<int> q;
}

您还必须在相应的 .cpp 文件中定义变量。

MyQueue.cpp:

#inclue "MyQueue.h"

static std::queue<int> MyQueue::q;

您可以通过包含该标题的任何文件访问它,例如:

MyQueue::q.push(2);

我仍然不建议这样做,尤其是在有多个线程的情况下,因为它是一个全局变量。

另一种选择是使用单例,但这也有同样的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    • 1970-01-01
    • 1970-01-01
    • 2012-01-14
    • 1970-01-01
    相关资源
    最近更新 更多