Вопрос по c++ – C ++ Singleton дизайн шаблона

619

Недавно я столкнулся с реализацией / реализацией шаблона проектирования Singleton для C ++. Это выглядело так (я взял это из примера из реальной жизни):

// a lot of methods are omitted here
class Singleton
{
   public:
       static Singleton* getInstance( );
       ~Singleton( );
   private:
       Singleton( );
       static Singleton* instance;
};

Из этого объявления я могу сделать вывод, что поле экземпляра инициируется в куче. Это означает, что есть выделение памяти. Что для меня совершенно неясно, когда именно память будет освобождена? Или есть ошибка и утечка памяти? Кажется, что есть проблема в реализации.

Мой главный вопрос: как мне правильно это реализовать?

Error: User Rate Limit ExceededbadError: User Rate Limit Exceeded derekerdmann
Error: User Rate Limit ExceededsometimesError: User Rate Limit ExceededhackError: User Rate Limit Exceeded sbi
Error: User Rate Limit Exceeded jwd
Error: User Rate Limit Exceededaristeia.com/Papers/DDJ%5FJul%5FAug%5F2004%5Frevised.pdf Matthieu N.
Error: User Rate Limit Exceededstackoverflow.com/questions/211237/…Error: User Rate Limit Exceededstackoverflow.com/questions/270947/…Error: User Rate Limit Exceededstackoverflow.com/questions/246564/…Error: User Rate Limit Exceededstackoverflow.com/questions/449436/…Error: User Rate Limit Exceededstackoverflow.com/questions/335369/… Martin York

Ваш Ответ

18   ответов
2

template<typename HeirT>
class Singleton
{
public:
    Singleton() = delete;

    Singleton(const Singleton &) = delete;

    Singleton &operator=(const Singleton &) = delete;

    static HeirT &instance()
    {
        static HeirT instance;
        return instance;
    }
};

class Test : public Singleton<Test>

11

Error: User Rate Limit ExceededError: User Rate Limit Exceeded

Error: User Rate Limit ExceededsingletonError: User Rate Limit ExceededsingletonError: User Rate Limit Exceeded

Error: User Rate Limit Exceededstd::shared_ptrError: User Rate Limit ExceededsingletonError: User Rate Limit Exceeded

class Singleton
{
public:
    Singleton(Singleton const&) = delete;
    Singleton& operator=(Singleton const&) = delete;

    static std::shared_ptr<Singleton> instance()
    {
        static std::shared_ptr<Singleton> s{new Singleton};
        return s;
    }

private:
    Singleton() {}
};
5

class S
{
    public:
        static S& getInstance()
        {
            if( m_s.get() == 0 )
            {
              m_s.reset( new S() );
            }
            return *m_s;
        }

    private:
        static std::unique_ptr<S> m_s;

        S();
        S(S const&);            // Don't Implement
        void operator=(S const&); // Don't implement
};

std::unique_ptr<S> S::m_s(0);
Error: User Rate Limit Exceededm_sError: User Rate Limit ExceededstaticError: User Rate Limit ExceededgetInstance()Error: User Rate Limit Exceeded
1

struct Store{
   std::array<Something, 1024> data;
   size_t get(size_t idx){ /* ... */ }
   void incr_ref(size_t idx){ /* ... */}
   void decr_ref(size_t idx){ /* ... */}
};

template<Store* store_p>
struct ItemRef{
   size_t idx;
   auto get(){ return store_p->get(idx); };
   ItemRef() { store_p->incr_ref(idx); };
   ~ItemRef() { store_p->decr_ref(idx); };
};

Store store1_g;
Store store2_g; // we don't restrict the number of global Store instances

main

auto ref1_a = ItemRef<&store1_g>(101);
auto ref2_a = ItemRef<&store2_g>(201); 

StoreStoreStoreItemReffriendStore

Store

template <typename Store_t, Store_t* store_p>
struct StoreWrapper{ /* stuff to access store_p, e.g. methods returning 
                       instances of ItemRef<Store_t, store_p>. */ };

StoreWrapperStoreStore).

941


.

class S
{
    public:
        static S& getInstance()
        {
            static S    instance; // Guaranteed to be destroyed.
                                  // Instantiated on first use.
            return instance;
        }
    private:
        S() {}                    // Constructor? (the {} brackets) are needed here.

        // C++ 03
        // ========
        // Don't forget to declare these two. You want to make sure they
        // are unacceptable otherwise you may accidentally get copies of
        // your singleton appearing.
        S(S const&);              // Don't Implement
        void operator=(S const&); // Don't implement

        // C++ 11
        // =======
        // We can use the better technique of deleting the methods
        // we don't want.
    public:
        S(S const&)               = delete;
        void operator=(S const&)  = delete;

        // Note: Scott Meyers mentions in his Effective Modern
        //       C++ book, that deleted functions should generally
        //       be public as it results in better error messages
        //       due to the compilers behavior to check accessibility
        //       before deleted status
};








Error: User Rate Limit Exceededstackoverflow.com/questions/1661529/…
Error: User Rate Limit Exceededvery well definedError: User Rate Limit Exceededstackoverflow.com/questions/246564/…
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
What irks me most though is the run-time check of the hidden boolean in getInstance()Error: User Rate Limit Exceededstackoverflow.com/a/335746/14065Error: User Rate Limit ExceededSchwarz counterError: User Rate Limit Exceededget_instance()Error: User Rate Limit Exceeded
0

6

main()main.

QApplicationmain

init()term()maingetInstance()

Error: User Rate Limit Exceeded Artem Barger
Error: User Rate Limit Exceeded
-1
#define INS(c) private:void operator=(c const&){};public:static c& I(){static c _instance;return _instance;}

   class CCtrl
    {
    private:
        CCtrl(void);
        virtual ~CCtrl(void);

    public:
        INS(CCtrl);
2

Singleton * Singleton::getInstance() {
    if (!instance) {
        instance = new Singleton();
    };
    return instance;
};

Error: User Rate Limit Exceeded Artem Barger
Error: User Rate Limit Exceeded
44

Error: User Rate Limit Exceeded
если удаление никогда не вызывается явно для статического экземпляра Singleton *, разве это технически не будет считаться утечкой памяти?
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
3

#include <Windows.h>
#include <iostream>

using namespace std;


class SingletonClass {

public:
    static SingletonClass* getInstance() {

    return (!m_instanceSingleton) ?
        m_instanceSingleton = new SingletonClass : 
        m_instanceSingleton;
    }

private:
    // private constructor and destructor
    SingletonClass() { cout << "SingletonClass instance created!\n"; }
    ~SingletonClass() {}

    // private copy constructor and assignment operator
    SingletonClass(const SingletonClass&);
    SingletonClass& operator=(const SingletonClass&);

    static SingletonClass *m_instanceSingleton;
};

SingletonClass* SingletonClass::m_instanceSingleton = nullptr;



int main(int argc, const char * argv[]) {

    SingletonClass *singleton;
    singleton = singleton->getInstance();
    cout << singleton << endl;

    // Another object gets the reference of the first object!
    SingletonClass *anotherSingleton;
    anotherSingleton = anotherSingleton->getInstance();
    cout << anotherSingleton << endl;

    Sleep(5000);

    return 0;
}

SingletonClass instance created!
00915CB8
00915CB8

-1

#ifndef SC_SINGLETON_CLASS_H
#define SC_SINGLETON_CLASS_H

class SingletonClass
{
    public:
        static SingletonClass* Instance()
        {
           static SingletonClass* instance = new SingletonClass();
           return instance;
        }

        void Relocate(int X, int Y, int Z);

    private:
        SingletonClass();
        ~SingletonClass();
};

#define sSingletonClass SingletonClass::Instance()

#endif

sSingletonClass->Relocate(1, 2, 5);
-5

class singleton
{
    static singleton *s;
    static unsigned char *buffer[sizeof(singleton)/4 *4] //4 byte align
    static singleton* getinstance()
    {
        if (s == null)
        {
            s = new(buffer) singleton;
        }
        return s;
    }
};
Error: User Rate Limit Exceeded
1

Error: User Rate Limit Exceededstd::call_onceError: User Rate Limit Exceededstd::once_flag? Most other approaches - including double checked locking - are broken.

Error: User Rate Limit Exceededstd::once_flagError: User Rate Limit Exceeded

33

class Singleton
{
private:
   Singleton();

public:
   static Singleton& instance()
   {
      static Singleton INSTANCE;
      return INSTANCE;
   }
};

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
9

Error: User Rate Limit ExceededCError: User Rate Limit Exceeded

singleton<C>()

Error: User Rate Limit Exceeded

template <class X>
X& singleton()
{
    static X x;
    return x;
}

Error: User Rate Limit Exceeded

Error: User Rate Limit Exceeded
Error: User Rate Limit Exceeded
-2

-1

Error: User Rate Limit Exceeded

Похожие вопросы