The Singleton Pattern in C++

What lies beyond the horizon?
singleton.cpp
C++
#pragma once
#include <string>
class Singleton {
public:
/// Deleted Singleton Copy Constructor
Singleton(Singleton const&) = delete;
/// Deleted Singleton Assignment Operator
void operator=(Singleton const&) = delete;
/// Static accessor method
static Singleton& Instance() {
static Singleton singleton;
return singleton;
}
void SetValue(const std::string& str) {
this->value_ = str;
}
std::string GetValue() {
return value_;
}
private:
/// Privatizing the Singleton default constructor
Singleton() = default;
/// Dummy member field for demonstration
std::string value_;
};
main.cpp
C++
#include <iostream>
#include "singleton.hpp"
int main() {
auto& singleton = Singleton::Instance();
singleton.SetValue("Hello World!");
std::cout << singleton.GetValue() << std::endl;
return 0;
}

Discover more from shared_ptr

Subscribe now to keep reading and get access to the full archive.

Continue reading