2016-07-21 3 views
1

나는 이것에 대해 link 새롭고 C++로 읽었습니다. 싱글 톤 패턴을 구현 한 코드가 있습니다. 나는이 코드를 테스트 한 :테스트시 "새 싱글로 삭제 및 삭제 (C++)"

#include <iostream> 
#include <memory> 

class Singleton { 
    static Singleton *instance; 
    static std::size_t refcount; 
    std::string _s; 

    public: 
    void setS(std::string s) { _s = s; } 
    std::string getS() { return _s; } 
    static void *operator new(std::size_t nbytes) throw (std::bad_alloc) { 
     std::cout << "operator new" << std::endl; 
     if (instance == nullptr) { 
      std::cout << "operator new nullptr" << std::endl; 
      instance = ::new Singleton; // Use the default allocator 
     } 
     refcount++; 
     return instance; 
    } 

    static void operator delete(void *p) { 
     std::cout << "operator delete" << std::endl; 
     if (--refcount == 0) { 
      std::cout << "operator delete" << refcount << std::endl; 
      ::delete instance; 
      instance = nullptr; 
     } 
    } 
}; 

Singleton *Singleton::instance = nullptr; 
std::size_t Singleton::refcount = 0; 

int main() { 
    Singleton* s = new Singleton; 
    //Singleton* t = new Singleton; 
    s->setS("string s"); 
    std::cout << "s " << s->getS() << std::endl; 
    Singleton* t = new Singleton; 
    std::cout << "t " << t->getS() << std::endl; 
    return 0; 
} 

을하지만 결과는 다음과 같습니다

operator new 
operator new nullptr 
s string s 
operator new 
t 

왜 t는 "문자열 s"를 인쇄하지 않았다? 주석 행을 변경하면 "문자열 s"가 출력됩니다.

+0

'* s == * t' 란 무엇입니까? – user4759923

+0

스택 할당 인스턴스는 어떻게 고려됩니까? – user2672165

+0

@ user4759923 : * s와 * t는 똑같이 하나뿐입니다. 그러나 Singleton에는 연산자 ==가 없습니다. 이 연산자를 정의하면 결과는 사용자에 따라 다릅니다. – aviit

답변

2

new Singleton 문은 operator new을 호출하여 저장소를 가져온 다음 기본 생성자를 사용하여 개체의 비 정적 멤버를 초기화합니다.

_s은 정적이 아니므로 새 Singleton을 만들 때마다 다시 초기화됩니다. 따라서 t의 빈 문자열이됩니다.

이렇게하면 _s 멤버의 공간을 다시 사용할 수 있습니다.

+0

저장소는 동일하지만 모든 비 정적 구성원을 (다시) 초기화 할 모든 새 표현식에 대해 생성자가 호출됩니다. – aviit