作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个简单的单例
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/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!