나는 이것에 대해 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"가 출력됩니다.
'* s == * t' 란 무엇입니까? – user4759923
스택 할당 인스턴스는 어떻게 고려됩니까? – user2672165
@ user4759923 : * s와 * t는 똑같이 하나뿐입니다. 그러나 Singleton에는 연산자 ==가 없습니다. 이 연산자를 정의하면 결과는 사용자에 따라 다릅니다. – aviit