I saw a piece of code from a website. It seems to be a simple example for a singleton class. Basically, the author creates an object in the definition of a class, which has the same name as the class. Inside the definition of the class, everything is public. One cannot instantiate another object. Is it that simple to create a singleton class? Is the all-public members in the class good enough in terms of encapsulation?
In the following is the code run successfully:
#include "stdafx.h"
#include<stdio. h>
#include <iostream>
using namespace std;
class singleton
{
public:
void print()
{
printf("hello\n ");
}
int a;
}singleton;
class client : public singleton
{};
int main()
{
// singleton s; // Can define an object before singleton
// singleton singleton;
// singleton b; #cannot define a new object after singleton
singleton.a=5;
printf("a=%d\n" ,singleton.a);
singleton.print ();
client xyz;
xyz.print();
xyz.a = 10;
cout << "xyz.a = " << xyz.a << endl;
return 0;
}
3 3136 gpraghuram 1,275
Recognized Expert Top Contributor
I saw a piece of code from a website. It seems to be a simple example for a singleton class. Basically, the author creates an object in the definition of a class, which has the same name as the class. Inside the definition of the class, everything is public. One cannot instantiate another object. Is it that simple to create a singleton class? Is the all-public members in the class good enough in terms of encapsulation?
In the following is the code run successfully:
#include "stdafx.h"
#include<stdio. h>
#include <iostream>
using namespace std;
class singleton
{
public:
void print()
{
printf("hello\n ");
}
int a;
}singleton;
class client : public singleton
{};
int main()
{
// singleton s; // Can define an object before singleton
// singleton singleton;
// singleton b; #cannot define a new object after singleton
singleton.a=5;
printf("a=%d\n" ,singleton.a);
singleton.print ();
client xyz;
xyz.print();
xyz.a = 10;
cout << "xyz.a = " << xyz.a << endl;
return 0;
}
Hi,
This is not the right way to create a singleton class and in the example the class name is singleton and not the implementaion is.
Search in thie forum fo singleton class in c++.
Raghuram
The singleton is a pattern where you want to make sure that no other instance can be created (you can look at "Effective C++" and "More Effective C++" from Scott Meyers).
Ex.1 -
class MySingleton {
-
public:
-
MySingleton() {
-
if (s_pInstance != NULL) {
-
// run-time error
-
}
-
}
-
-
~MySingleton() {
-
if (s_pInstance != NULL) {
-
delete s_pInstance;
-
s_pInstance = NULL;
-
}
-
}
-
-
private:
-
// prevents that an object of the class get copied
-
// ex: MySingleton s2(s1);
-
// ex: s2 = s1;
-
MySingleton(const MySingleton&);
-
MySingleton& operator=(const MySingleton&);
-
-
static MySingleton* s_pInstance;
-
};
-
-
// in C++ file
-
MySingleton* MySingleton::s_pInstance = NULL;
-
-
In this example, it does a run-time check on the existence of a MySingleton instance. -
class MySingleton2 {
-
public:
-
static MySingleton2& GetInstance();
-
-
private:
-
MySingleton2() {
-
// ...
-
}
-
-
~MySingleton2() {
-
// ...
-
}
-
};
-
-
// in C++ file
-
MySingleton2& MySingleton2::GetInstance()
-
{
-
static MySingleton2 theInstance;
-
return theInstance;
-
}
-
-
In this example, the CTOR and DTOR are private, and the unique instance will be created on demand only, whenever GetInstance() gets called, so there is no error upon rt check.
I saw a piece of code from a website. It seems to be a simple example for a singleton class. Basically, the author creates an object in the definition of a class, which has the same name as the class. Inside the definition of the class, everything is public. One cannot instantiate another object. Is it that simple to create a singleton class? Is the all-public members in the class good enough in terms of encapsulation?
In the following is the code run successfully:
#include "stdafx.h"
#include<stdio. h>
#include <iostream>
using namespace std;
class singleton
{
public:
void print()
{
printf("hello\n ");
}
int a;
}singleton;
class client : public singleton
{};
int main()
{
// singleton s; // Can define an object before singleton
// singleton singleton;
// singleton b; #cannot define a new object after singleton
singleton.a=5;
printf("a=%d\n" ,singleton.a);
singleton.print ();
client xyz;
xyz.print();
xyz.a = 10;
cout << "xyz.a = " << xyz.a << endl;
return 0;
}
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: cppaddict |
last post by:
Hi,
In this tutorial on singleton class in C++
(http://gethelp.devx.com/techtips/cpp_pro/10min/10min0200.asp) the
author gives two implementations of a simple singleton class, claiming
that only the first is safe for multi-threaded appliactions. I want
to know why this so.
The class is as follows:
|
by: Ethan |
last post by:
Hi,
I have a class defined as a "Singleton" (Design Pattern). The codes are
attached below.
My questions are:
1. Does it has mem leak? If no, when did the destructor called? If yes, how
can I avoid it? Purify does not show it has mem leak.
// test if singleto class has mem leakage
#include <iostream>
|
by: Pelle Beckman |
last post by:
Hi,
I've done some progress in writing a rather simple
singleton template.
However, I need a smart way to pass constructor arguments
via the template.
I've been suggested reading "Modern C++ Design" or similar
books, but I feel there are full of clever guys here
who could help me out.
|
by: Preets |
last post by:
Can anyone explain to me the exact use of private constructors in c++ ?
|
by: toton |
last post by:
Hi,
If I have a singleton class based on dynamic initialization (with new
) , is it considered a memory leak? Anything in C++ standard says about
it ?
And little off - topic question ,
If the singleton is initialized as a static variable , it seems
there is some threading issue . Is it the issue during singleton
initialization only , or during the access also?
If the singleton is per thread basis (then no more singleton though
), and...
| |
by: Damien |
last post by:
Hi all,
I'm using a pretty standard C++ Singleton class, as below:
template <typename T>
class Singleton
{
public:
static T* Instance()
{
|
by: weaknessforcats |
last post by:
Design Pattern: The Singleton
Overview
Use the Singleton Design Pattern when you want to have only one instance of a class. This single instance must have a single global point of access. That is, regardless of where the object is hidden, everyone needs access to it.
The global point of access is the object's Instance() method.
Individual users need to be prevented from creating their own instances of the Singleton.
|
by: Bob Johnson |
last post by:
Just wondering the extent to which some of you are implementing classes as
Singletons. I'm working on a brand new project and, early on, identified
some obvious candidates. By "obvoius candidates" I mean classes for which
terrible problems would clearly arise if more than one instance were to
exist. But as I'm getting into the design of this new solution, I'm
realizing that a large percentage of the classes _could be_ implemented as...
|
by: John Doe |
last post by:
Hi,
I have a singleton class defined like this :
class UIManager : public CSingleton<UIManager>,
public CObject
{
protected:
DECLARE_DYNAMIC(UIManager)
friend class CSingleton<UIManager>;
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |