gpt4 book ai didi

c++ - 是否可以有应用程序级别的单例?

转载 作者:行者123 更新时间:2023-11-30 02:33:54 26 4
gpt4 key购买 nike

我有一个简单的单例

  class Options {
private:
Options()
{};
Options(Options const&);
void operator=(Options const&);
public:
static Options& get()
{
static Options INSTANCE;
return INSTANCE;
}
};

我在共享库 A 的 header 中得到了这个定义

但是当我首先从应用程序 B 调用 get() 时,我看到实例是如何创建的,然后我从共享库 C 调用方法并使用 get() 在那里我得到了另一个实例......

我怎样才能拥有类似应用程序级别的单例? (是否有 extern 关键字?)

最佳答案

它应该在提供的 windows 下工作:

  • 您始终使用 __declspec(dllexport) 进行导出,使用 __declspec(dllimport) 进行导入
  • Options::get() 的实现被移动到一个 cpp 文件中,因此它只存在于 DLL 中。

这是一个例子:

options.dll 使用定义的 OPTIONS_EXPORT 符号构建:

选项.h:

#pragma once

#ifdef OPTIONS_EXPORTS
#define DLLAPI __declspec(dllexport)
#else
#define DLLAPI __declspec(dllimport)
#endif

class DLLAPI Options
{
private:
Options()
{};
Options(Options const&);
void operator=(Options const&);
public:
static Options& get();
int val;
};

选项.cpp:

#include "Options.h"

Options& Options::get()
{
static Options INSTANCE;
return INSTANCE;
}

使用 options.dll 构建的虚拟 c.dll 定义了 C_EXPORT 符号并与 options.lib 链接:

c.h:

#pragma once

#ifdef C_EXPORTS
#define dll __declspec(dllexport)
#else
#define dll __declspec(dllimport)
#endif

#include "../a/options.h"

namespace C {
dll Options& relay();
};

c.cpp:

#include "c.h"

Options& C::relay() {
Options& opt = Options::get();
return opt;
}

还有一个与 options.dll 和 c.dll 链接的最小主链接:

#include <iostream>
#include "../a/options.h"
#include "../c/c.h"

int main() {
Options& o1 = Options::get();
o1.val = 12;
Options& o2 = C::relay();

std::cout << ((o1.val == o2.val) ? "Ok" : "Ko") << std::endl;
return 0;
}

输出符合预期:Ok

关于c++ - 是否可以有应用程序级别的单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34987433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com