linux多实例,c++ 在Linux上的共享库中的单例的多个实例

我的问题,正如标题所提到的,是显而易见的,我详细描述的情况。

有一个名为singleton的类通过singleton模式实现,如下所示,在文件singleton.h中:

/*

* singleton.h

*

* Created on: 2011-12-24

* Author: bourneli

*/

#ifndef SINGLETON_H_

#define SINGLETON_H_

class singleton

{

private:

singleton() {num = -1;}

static singleton* pInstance;

public:

static singleton& instance()

{

if (NULL == pInstance)

{

pInstance = new singleton();

}

return *pInstance;

}

public:

int num;

};

singleton* singleton::pInstance = NULL;

#endif /* SINGLETON_H_ */

然后,有一个名为hello.cpp的插件如下:

#include

#include "singleton.h"

extern "C" void hello() {

std::cout << "singleton.num in hello.so : " << singleton::instance().num << std::endl;

++singleton::instance().num;

std::cout << "singleton.num in hello.so after ++ : " << singleton::instance().num << std::endl;

}

你可以看到插件调用单例并更改单例中的属性num。

最后,有一个main函数使用单例和插件如下:

#include

#include

#include "singleton.h"

int main() {

using std::cout;

using std::cerr;

using std::endl;

singleton::instance().num = 100; // call singleton

cout << "singleton.num in main : " << singleton::instance().num << endl;// call singleton

// open the library

void* handle = dlopen("./hello.so", RTLD_LAZY);

if (!handle) {

cerr << "Cannot open library: " << dlerror() << '\n';

return 1;

}

// load the symbol

typedef void (*hello_t)();

// reset errors

dlerror();

hello_t hello = (hello_t) dlsym(handle, "hello");

const char *dlsym_error = dlerror();

if (dlsym_error) {

cerr << "Cannot load symbol 'hello': " << dlerror() << '\n';

dlclose(handle);

return 1;

}

hello(); // call plugin function hello

cout << "singleton.num in main : " << singleton::instance().num << endl;// call singleton

dlclose(handle);

}

并且makefile如下:

example1: main.cpp hello.so

$(CXX) $(CXXFLAGS) -o example1 main.cpp -ldl

hello.so: hello.cpp

$(CXX) $(CXXFLAGS) -shared -o hello.so hello.cpp

clean:

rm -f example1 hello.so

.PHONY: clean

所以,什么是输出?

我以为有以下:

singleton.num in main : 100

singleton.num in hello.so : 100

singleton.num in hello.so after ++ : 101

singleton.num in main : 101

然而,实际输出如下:

singleton.num in main : 100

singleton.num in hello.so : -1

singleton.num in hello.so after ++ : 0

singleton.num in main : 100

它证明有两个单例类的实例。

为什么?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值