- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Meyer 的单例类蓝图在头文件 temp.h 中声明。如果 temp.h 包含在两个单独的 .cpp 文件中,那么每个文件都有自己的蓝图,并且静态的东西对其他模块(即 *.o 或 *.cpp)不可见,因此每个 .cpp 文件都应该有自己的对象临时类(表示程序中临时的两个实例)。但是我已经在程序中检查过了,两个 .cpp 文件之间共享相同的实例。我不明白为什么?
//temp.h
class temp
{
public:
~temp() {}
void temp_func()
{
std::cout << "Inside temp_func" << "\n";
}
static temp& createInstance()
{
static temp ins;
return ins;
}
priave:
temp() {}
};
另一个头文件,没有类实例(内置数据类型)
//temp1.h
inline static int& createInstance()
{
static int ins;
return ins;
}
//another.cpp
#include "temp1.h"
void func()
{
int &t = createInstance();
std::cout << "t: " << t << "\n";
t = 20;
}
//main.cpp
#include "temp1.h"
void func();
int main()
{
int &temp = createInstance();
temp = 10;
std::cout << "temp:" << temp << "\n";
func();
std::cout << "temp:" << temp << "\n";
return 0;
}
程序输出
temp:10
t: 0
temp:10
最佳答案
检查这个inline关键词解释。引用:
There may be more than one definition of an inline function or variable (since C++17) in the program as long as each definition appears in a different translation unit and (for non-static inline functions and variables (since C++17)) all definitions are identical. For example, an inline function or an inline variable (since C++17) may be defined in a header file that is #include'd in multiple source files.
您的 createInstance
函数就是那种函数 - 因为您已经在类定义中定义了它,所以它是隐式内联的。因此,编译器会将它们合并在一起,就好像它们只是一个。因此,您的函数将返回相同的 ins
对象。
请注意,该函数必须是内联
,否则会发生其他事情 - 您违反了one definition rule ,准确地说:
One and only one definition of every non-inline function or variable that is odr-used (see below) is required to appear in the entire program (including any standard and user-defined libraries). The compiler is not required to diagnose this violation, but the behavior of the program that violates it is undefined.
编辑:在第二种情况下,它与内置类型数据无关,而是关于将 createInstance
函数移到类之外。它能做什么?它改变了您添加到函数定义中的 static
关键字的含义 - 现在该函数将被复制(而不是在链接时共享或合并在一起),因此每次翻译unit 获取它自己的 int ins
变量拷贝。删除 static
关键字:
//temp1.h
inline int& createInstance()
{
static int ins;
return ins;
}
而且效果很好:
temp:10
t: 10
temp:20
关于c++ - 函数内部带有静态变量的单例类(Meyer 的实现),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57060478/
我最近购买了《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
我是一名优秀的程序员,十分优秀!