如何在共享库的整个生命周期中存储数据

How to store data through the life of a shared library

我正在用 C++ 编写一个共享库,它将通过 JNI 调用。我有一个 class 接收来自 Java 的消息并转发给适当的对象。我们称它为 Dispatcher。有一个 DataStore 必须存在于程序的整个生命周期中。实际上,在 JNI 次调用之间必须可以访问某些数据。

我当前的草图由两个 classes 作为单身人士组成。 DataStore 看起来像这样:

class DataStore {
    // constructors, get_instance() etc. are skipped
    int _read_only_variable{};
public:
    DataStore (int param) : _read_only_variable(param) {}
    // or
    void set_data(int param) {
        _read_only_variable = param
    }
};

如何保证只有Dispatcher对象才能创建DataStore对象或者只有Dispatcher才能调用set_data

从另一方面来说,如果我保证 _read_only_variable 真的只写在构造函数中,那将确保只存在一个实例。

我也想符合 SOLID 原则,因此我会避免嵌套 classes.

您可以保证只有 Dispatcher 调用这些方法,方法是将它们设为私有,然后将 Dispatcher 设为 friend

P.S。 _read_only_variable 在 C++ 中将是 const。编译器会大声抱怨你试图修改它。但它只保证每个数据存储有一个 _read_only_variable ,这非常简单,不是您想要的。