我正在使用 C++ 在 Linux 上设计一个线程安全的单例类boost::call_once
。
我收到以下编译器错误:
/tmp/ccLanvZI.o: In function `SingleTon::getInstance()':
singleTon.cpp:(.text._ZN9SingleTon11getInstanceEv[SingleTon::getInstance()]+0x1b): undefined reference to `SingleTon::p'
/tmp/ccLanvZI.o: In function `SingleTon::makeInstance()':
singleTon.cpp:(.text._ZN9SingleTon12makeInstanceEv[SingleTon::makeInstance()]+0x21): undefined reference to `SingleTon::SingleTon()'
singleTon.cpp:(.text._ZN9SingleTon12makeInstanceEv[SingleTon::makeInstance()]+0x2c): undefined reference to `SingleTon::p'
collect2: ld returned 1 exit status
make: *** [singlton] Error 1
看到一些帖子后,我仍然不知道如何处理这个错误。如何更改void (SingleTon::)()
为void (*)()
?
#include <iostream>
#include <pthread.h>
#include <boost/thread/mutex.hpp>
#include <boost/thread/once.hpp>
#include <boost/bind.hpp>
#include <boost/threadpool.hpp>
#include <boost/thread/thread.hpp>
boost::once_flag flag = BOOST_ONCE_INIT;
class SingleTon
{
private:
static SingleTon *p;
SingleTon();
SingleTon(const SingleTon&);
SingleTon& operator=(const SingleTon&);
void makeInstance();
public:
SingleTon* getInstance();
~SingleTon()
{
if (p)
delete p;
}
};
void SingleTon::makeInstance()
{
p = new SingleTon;
return;
}
SingleTon* SingleTon::getInstance()
{
boost::call_once( makeInstance , flag); // error !!!
return p;
}
int main()
{
SingleTon *s;
s = SingleTon::getInstance();
return 0;
}