Конструктор помечается модификатором private, чтобы объект класса нельзя было создать извне
class Sun { public: static shared_ptr<Sun> instance() { class SunProxy : public Sun {}; static shared_ptr<Sun> myInstance = make_shared<SunProxy>(); return myInstance; } ~Sun() { cout << "Calling the destructor;" << endl; } void shine() { cout << "The sun is shining;" << endl; } Sun(const Sun&) = delete; Sun& operator =(const Sun&) = delete; private: Sun() { cout << "Calling the default constructor;" << endl; } };
# include <iostream> # include <memory> using namespace std; int main() { shared_ptr<Sun> sun(Sun::instance()); sun->shine(); }
Last updated 11 months ago
Was this helpful?
Singleton