c++ - std::function 分配在 Visual C++ 2015 Win32 应用程序中无效

标签 c++ winapi

这是我的场景:

主要.cpp

#include <Windows.h>
#include <functional>

std::function<void()> OnPrepare;

int WINAPI WinMain(HINSTANCE inst, HINSTANCE preInst, TCHAR*, int) {
    if (OnPrepare) {
        OnPrepare();
    }

    return 0;
}

其他.cpp

#define _AFXDLL
#include <afx.h>  // TRACE
#include <functional>

extern std::function<void()> OnPrepare;

class Init {
public:
    Init() {
        OnPrepare = []() {
            TRACE("hello, world!\n");
        };
    }
};

Init g_init;

此代码在 Win32 应用程序中不起作用,但在控制台应用程序中运行良好。我不知道为什么。谁能指出我的代码有什么问题?如果我不能这样做,有没有更好的方法?

编辑:

OnPrepare 在 Win32 应用程序中始终为 null,因此不会出现 "hello, world"

最佳答案

构造g_init的代码修改了OnPrepare。当然,只有当 OnPrepare 已经构建时,这才是合法的。但是,如果 g_init 是在 OnPrepare 之前构造的呢?然后您将修改一个尚未构造的对象,然后再构造一个您已经修改过的对象。哎哟。在静态对象的构造函数中进行实际工作从来都不是一个好主意。

不清楚你的外部问题是什么,但这段代码不是解决它的好方法。一个丑陋的解决方法是将全局 std::function 替换为全局函数,该函数返回对函数 static std::function 的引用并使用它。这确保对象在被分配之前被构建。

std::function<void()>& getOnPrepare()
{
    static std::function<void()> OnPrepare;
    return OnPrepare;
}

然后 Init 的构造函数可以调用 getOnPrepare,确保 OnPrepare 在分配给之前构造:

Init() {
    getOnPrepare() = []() {
        TRACE("hello, world!\n");
    };

关于c++ - std::function 分配在 Visual C++ 2015 Win32 应用程序中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53652464/

相关文章:

c++ - 使用 Qt 编写安全的服务器应用程序

c++ - c++中数组只存储token的第一个字符

windows - Windows 7之前的计时器合并

c - 进程的标准输出未通过 dll 注入(inject)正​​确重定向

c++ - 等待线程

c++ - 在apache2上配置cgi

c++ - 为什么我不能使用 fopen?

c++ - 系统错误 0x5 : CreateFileMapping()

c++ - Win32 API : App Freezes after opening dialog window

c++ - 使用带有 QModelIndexes 列表的 concurrent::map()