NULL_CLASS_PTR_DEREFERENCE 在日志宏中使用 __FILE__、__LINE__ 和 __FUNCTION__ 时

NULL_CLASS_PTR_DEREFERENCE when using __FILE__, __LINE__ and __FUNCTION__ in log macro

我的一个程序有一个奇怪的行为。我定义了一个扩展为

的宏 LOG_FUNCTION
#define LOG_FUNCTION \
    { \
        std::string strFile = __FILE__; \
        std::string strLine = std::to_string(__LINE__); \
        std::string strFunction = __FUNCTION__; \
        logger.log(strFile + ", line " + strLine + ", " + strFunction + "()"); \
    } \
    CIndentor _indentor_(&logger);

在 Logger.h 中声明。记录器也在 Logger.h:

中声明
// Declare the one and only logger object (which is defined in Logger.cpp):
extern CLogger logger;

日志函数如下所示:

void CLogger::log(const string &strText)
{
    lock_guard<mutex> lockGuard(_mutex);

    m_count++;

    string strIndentation(m_indentation, ' ');

    string strTime = getCurrentDateTime();

    FILE* pFileStream = nullptr;
    errno_t err = fopen_s(&pFileStream, m_strLogFilePath.c_str(), "a+");
    if (err == 0)
    {
        fprintf(pFileStream, "[#%05d] [%s] %s%s\n", m_count, strTime.c_str(), strIndentation.c_str(), strText.c_str());  
        fclose(pFileStream); 
    }
}

现在有时我的程序会崩溃。 使用 windbg 检查 heapdump 这恰好发生在我在我的一个函数中调用 LOG_FUNCTION-macro 的代码行。这并不总是发生,当然我也在其他没有发生此类崩溃的地方使用宏。仅在单个函数中(第一行):

void MyClass::SetInfoText(wstring& text)
{
    LOG_FUNCTION;  // <= this is the place where windbg says it crashes
    ...
}

任何人都可以阐明这一点吗?

编辑

在上面添加了一些代码以显示声明记录器的位置

NULL_CLASS_PTR_DEREFERENCE 表示带有 this 指针的东西是错误的 - thisNULL.

如果在通过此 nullptr 访问的第一个成员的空指针上调用非虚拟成员函数,则可能会发生这种情况 this

您需要回顾一下堆栈并确保调用方站点不会发生这种情况。