The problem of creating C ++ Singleton

I recently purchased some code that I want to connect to Linux. However, in the header file, I have a curious code that I hope someone can shed some light on. Inside the header file inside the namespace where other classes are defined, I have the following:

#define CREATE_SINGLETON_METHODS(s) \
  private: \
    friend class Singleton<c>; \
    ##c(); \
    virtual ~##c();

I understand that it’s a ##marker insertion operation, but I can’t understand why the original author used it (which I don’t know and can’t contact). I have an implementation class that looks like this:

class MapManager : public Singleton<MapManager> {
CREATE_SINGLETON_METHODS(MapManager)

private:
...

When compiling, I get the following error:

error: pasting ";" and "MapManager" does not give a valid preprocessing token

This compilation is found on Windows and some earlier versions of gcc (pre 4.x). Any ideas on what could be happening here? Thanks!

+3
source share
8

singleton: :

#ifndef SINGLETON_HPP_STYLET
#define SINGLETON_HPP_STYLET 0


/*
*
*
*   Generic Singleton implementation
*
*
*/ 


        template <class T>
        class SingletonHolder : public T
        {
            public:                                  
                static SingletonHolder<T>& getInstance()
                {

                    static SingletonHolder<T> instance;
                    return instance;
                }

            private:
                SingletonHolder()
                {
                };

                virtual ~SingletonHolder()
                {
                };

        };//class SingletonHolder



#endif //SINGLETON_HPP_STYLET

//------------------------------------------ ------------------------

:

SomeClass;

typedef SingletonHolder<SomeClass> SomeClassSingleton;


SomeClassSingleton::getInstance().doSomething();
+2

##, . . , , , .

+1

:

#define CREATE_SINGLETON_METHODS(c) \
  private: \
    friend class Singleton<c>; \
    c(); // Note the change on this line! \
    virtual ~##c();

##. ";" "c()"; gcc 4.

+1

, "" ( ) , . , , . .

+1

"" ( "#" "##" ) . , , ( , ).

.

+1

-. :

g++ -E mytestfile.h

( , ) , , . , . gcc 3.4.4 , , 4.x( Visual Studio 2008).

:

#define CREATE_SINGLETON_METHODS(c) \
private: \
friend class Singleton<c>; \
c(); \
virtual ~c();

( -E):

private: friend class Singleton<MapManager>; MapManager(); virtual ~MapManager();

.

http://gcc.gnu.org/onlinedocs/gcc-4.0.4/cpp/Tokenization.html:

, , , `## ' . . .

'##' . , , , , "; MapManager()" , 4.x .

(http://gcc.gnu.org/onlinedocs/cpp/Concatenation.html#Concatenation) :

'##' . , , "##".

, .

+1

? , :

#define CREATE_SINGLETON_METHODS(c) \
  private: \
    friend class Singleton<c>; \
    ##c(); \
    virtual ~##c();

, , , .

0

. , , .

If I were you, I would simply manually rewrite the related code for the affected classes. Macros are bad news for such things.

-1
source

Source: https://habr.com/ru/post/1711124/


All Articles