查询的类成员返回错误的值

Queried class member returns wrong value

本文关键字:错误 返回 成员 查询      更新时间:2023-10-16

我在我的一个DLL(我们称之为exporting DLL)中创建了一个简单的RAII类,它监视我的应用程序中的配置恢复:


头文件

class __declspec(dllexport) CEmuConfigurationRestoreMonitor
{
public:
    CEmuConfigurationRestoreMonitor()
    {
        m_restoreInProgress = true;
    }
    ~CEmuConfigurationRestoreMonitor()
    {
        m_restoreInProgress = false;
    }
    static bool IsRestoreInProgress()
    {
        return m_restoreInProgress;
    }
private:
    static bool m_restoreInProgress;
};

源文件

bool CEmuConfigurationRestoreMonitor::m_restoreInProgress = false;

其想法是exporting DLL中的恢复代码将在堆栈上实例化CEmuConfigurationRestoreMonitor,当它在方法结束时超出范围时,该标志将关闭

问题是,我想使用IsRestoreInProgress()从另一个DLL(比如importing DLL)查询标志。这就是为什么我将__declspec(dllexport)放在exporting DLL的类声明中。

当我链接importing DLL时,我得到了一个未解析的m_restoreInProgress符号。因此,我在importing DLL中的.cpp文件中添加了以下行,它修复了这个问题:

bool CEmuConfigurationRestoreMonitor::m_restoreInProgress = false;

我现在发现,即使m_restoreInProgress设置为true,当我从importing DLL查询它时,它总是返回false

importing DLL中的静态初始化是否以某种方式覆盖了exporting DLL中的实际(当前)值?

您为每个DLL提供了自己的m_restoreInProgress副本。

您可以通过以下方式解决此问题:

  • 未使用内联函数
  • 在仅包含在导出DLL中的源文件中,为m_resotreInProgress使用文件范围的变量