【问题标题】:multi file access to singleton class单例类的多文件访问
【发布时间】:2015-12-07 10:59:09
【问题描述】:

我有一个单例课程。

在 A.h 中

class single
{
    public:
        static single *Instance;
        static single* getInstance()
        { if(!Instance) Instance = new single; 
          return Instance;
        }
        void hello () { cout<<"Hello"; }
    private: single(){ }
}

在 A.cpp 中

single *single::Instance = 0;
std::auto_ptr <single> SINGLE_OBJ (single::getInstance());

在 B.cpp 中

#include "A.h"

SINGLE_OBJ->hello();

我收到以下错误: SINGLE_OBJ 未在此范围内声明。

【问题讨论】:

  • 为什么实例的内存是通过auto_ptr对外管理的?它使用new 分配的事实是一个实现细节。它应该保留在single 的内部以进行封装,并确保即使用户没有将指针放在auto_ptr 中也能清理内存。顺便说一句,C++11 将已弃用的 std::auto_ptr 类模板替换为 std::unique_ptr

标签: c++ singleton global-variables


【解决方案1】:

要使SINGLE_OBJB.cpp 中可见,您应该在A.h. 中声明它,即:

extern std::auto_ptr <single> SINGLE_OBJ;

另外,你为什么使用std::auto_ptr,它已被弃用 - 你应该切换到std::unique_ptr

【讨论】:

  • 当我编译代码并成功创建“.o”和“.so”时效果很好。但是,当另一个应用程序尝试使用此“.o”或“.so”时,我收到一条错误消息,指出未定义对 SINGLE_OBJ 的引用
  • @user2524261 你可能想开始一个新问题,你没有提到你想在共享库中使用它。对我来说,这听起来像是编译中的一些错误命令,即。看这里:stackoverflow.com/questions/12748837/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多