Hi guys ,i came across coding in a book where they given the below program and named it as singleton class.but here we are able to create 2nd object and also call constructor for second object (only here do we check the status of count and exit from the program after creation of 2nd object).so what if i am right??n what if i can modify this program and make it create only one object??

#include<iostream.h>
class sample
{
    static int count;
    public:
        sample()
        {
            if(count==1)
                exit(0);
                printf("OBJ:%d\n",count);
            count++;
        }
};
int sample::count;
int main()
{
    sample s1;
    sample s2;
    return(0);
}

Dani AI

Generated

— your example is not a true singleton. It lets a second object be constructed and then aborts the program, which is neither “one and only one instance” nor a graceful way to enforce it. was right to flag the use of exit() (it bypasses normal cleanup) and the general bad-mix of C/C++ style. ’s “google” hint is useful, but here’s a concise, modern way to do this in C++.

A simple, correct C++11+ singleton (lazy, thread-safe initialization, non-copyable):

class Sample {
public:
    static Sample& instance() {
        static Sample inst;   // created on first use, C++11 guarantees thread-safe init
        return inst;
    }

    Sample(const Sample&) = delete;
    Sample& operator=(const Sample&) = delete;

private:
    Sample() = default;
    ~Sample() = default;
};

Notes and practical cautions:

  • This prevents copies and provides one shared instance without terminating the process. C++11 guarantees the local static is initialized in a thread-safe way (cppreference).
  • Be aware of static destruction-order issues if other globals use the singleton during teardown. If that matters, consider controlled lifetime techniques (e.g., std::shared_ptr held by a function-local static, or deliberately leaking the instance) or explicit startup/shutdown management.
  • Prefer passing dependencies (dependency injection) over hidden globals when possible; singletons make testing and reasoning harder. See the C++ FAQ on singletons for common pitfalls and alternatives (isocpp wiki).

This approach fixes the core problems in your original snippet: it never lets a second distinct object exist, it doesn’t abort the program, and it follows modern C++ practice.

Recommended Answers

All 5 Replies

1. Always use code tag for your snippets (aee this forum rules):
[code=c++] source

[/code]
2. It's a very bad code. Avoid C++ program termination by C library function exit(). It don't call destructors so you can't terminate the program gracely. Probably the only proper method is an exception raising,
3. What's a strange C++/C mixture code with deprecated <iostream.h> and printf...
4. Why return(0) ? Keep it simpler: return 0 . Don't ignore common practice: start you class names from the capital letter (Sample),,,

hi arkm,i would take your suggestion and improve myself and i'm really sorry for posting c++/c mixture code...exact code is like this...

#include<iostream.h>
class Sample
{
static int count;
public:
Sample()
{
if(count==1)
exit(0);
count++;
}
};
int Sample::count;
int main()
{
Sample s1;
Sample s2;
return(0);
}

i do know that it really is a bad code...but i would like to know whether it forms a singleton class or not??

Member Avatar for Member #248612

google("c++ singleton");

hi jencas ,thanks for your suggestion and i've already google searched it and this was one of the simple as well as bad code i came across .so i would just like to know whether it forms a singleton class or not??

The point of a singletone pattern is not a punishment the program for the second or third class instantiations. You must provide a program with one and only one object of a singleton class. So you present a stub of a singleton class implementation mechanics (one of possible ones) but this "declaration bomb" is not a good singletone class as such (especially with that barbaric exit)...
Look at:



...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.