0

contents of three files are in the following, and then I use g++ command like this to compile them:

g++ singleton_template_thread.cpp singleton_template_thread_safe.cpp -o /tmp/stts

the error is:

/tmp/ccfFdxaW.o: In function `main':
singleton_template_thread.cpp:(.text+0x9): undefined reference to `SingletonTTS<Book>::Instance()'
collect2: error: ld returned 1 exit status

I don't know where the error is, I compile multi cpp files like this all the time

singleton_template_thread_safe.h is here

singleton_template_thread_safe.cpp

#include "singleton_template_thread_safe.h"

static int count = 0;

template <typename T>
T * SingletonTTS<T>::m_pInstance = nullptr;

template <typename T>
std::mutex SingletonTTS<T>::m_mutex;

template <typename T>
T * SingletonTTS<T>::Instance(){
    if(m_pInstance = nullptr){
        m_mutex.lock();
        if(m_pInstance = nullptr){
            m_pInstance = new T(count); 
            ++count;
        }
        m_mutex.unlock();
    }
    return m_pInstance;
}

template <typename T>
void SingletonTTS<T>::Destroy(){
    if(m_pInstance){
        m_mutex.lock();
        if(m_pInstance){
            delete m_pInstance;
            m_pInstance = nullptr;
        }
        m_mutex.unlock();
    }
}

singleton_template_thread.cpp

#include "singleton_template_thread_safe.h"
#include <iostream>
#include <thread>

int main()
{
    using namespace std;
    Book *b1 = SingletonTTS<Book>::Instance();

    return 0;
}
辛文飞
  • 1
  • 2
  • Unrelated: If your use case doesn't include being able to `Destroy` the singleton before the end of the program, you should [take a look at the Meyers Singleton](https://stackoverflow.com/a/1008289/4581301. It's a lot easier to manage than what you've currently got. – user4581301 Dec 17 '20 at 06:22
  • I have solved this problem, this https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file post maybe helpful to me, your answer isn't what I expect. – 辛文飞 Dec 17 '20 at 06:49

0 Answers0