C++: Undefined reference to instance in Singleton class(C ++:对单例类中的实例的未定义引用)
问题描述
我目前正在尝试将工厂实现为单例.我实际上使用了单例模式的教科书示例.这是 .h 文件:
I'm currently trying to implement a factory as a singleton. I practically used the textbook example of the Singleton pattern. Here's the .h file:
namespace oxygen{
class ImpFactory{
public:
static boost::shared_ptr<ImpFactory> GetInstance();
private:
static boost::shared_ptr<ImpFactory> mInstance;
};
这是 .cpp 文件:
and here's the .cpp file:
#include "impfactory.h"
using namespace oxygen;
using namespace boost;
shared_ptr<ImpFactory> ImpFactory::GetInstance(){
if (mInstance.get() == 0)
mInstance = shared_ptr<ImpFactory>(new ImpFactory());
return mInstance;
}
代码编译,但出现链接器错误:
The code compiles, but I get a linker error:
../../lib/oxygen/liboxygen.so.3.2.4:未定义对 `oxygen::ImpFactory::mInstance' 的引用
../../lib/oxygen/liboxygen.so.3.2.4: undefined reference to `oxygen::ImpFactory::mInstance'
目前有三名学生难倒.有什么想法吗?
This currently has three students stumped. Any ideas?
推荐答案
您必须定义静态实例,而不仅仅是声明它.该定义创建了您引用的实际对象.
You must define the static instance, not just declare it. The definition creates the actual object you refer to.
在您的 cpp
文件中,添加以下行:
In your cpp
file, add the line:
boost::shared_ptr<ImpFactory> ImpFactory::mInstance;
这篇关于C ++:对单例类中的实例的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C ++:对单例类中的实例的未定义引用


基础教程推荐
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01