Skip to main content
GameDev.net gamedev.net
🔒 Locked

Singleton solution w/ auto_ptr?

Started by cozman Feb 17, 2005 at 10:12 PM 15 replies 6.4k views
Original Post
cozman
cozman
I was toying around with creating a generic Singleton class. I was wondering if any of you could comment on this idea:
#include <cassert>
#include <memory>
#include <iostream>

template<class T>
class Singleton
{
public:   
    static void initSingleton()
    {
        assert(instance_.get() == 0);
        
        instance_ = std::auto_ptr<T>(new T);
    }

    static T& getSingleton()
    {
        assert(instance_.get() != 0);
        
        return *instance_;
    }
    
    static void destroySingleton()
    {
        assert(instance_.get() != 0);
        
        instance_.reset();
    }

    virtual ~Singleton()=0;

private:
    
    static std::auto_ptr<T> instance_;
};

template<class T> 
std::auto_ptr<T> Singleton<T>::instance_(0);

template<class T>
Singleton<T>::~Singleton() { }

class Something : public Singleton<Something>
{
    friend class Singleton<Something>;
    friend class std::auto_ptr<Something>;
private:
    Something() { std::cout << "created" << std::endl; }
    ~Something() { std::cout << "destroyed" << std::endl; }
};

From basic testing it works fine, you can't leak memory, but you can also control the order of destruction if it is important. Does anyone have any suggestions?
Drew_Benton
Drew_Benton
Hey! Here are my comments:

1. Not VC6 compatible. Compiled fine in VC7, Dev-CPP, and MFC. Just a FYI.
2. Worked great in a basic test in VC7 and Dev.
3. Easily intergrated into my MFC OpenAL Audio Library test project (~3000 lines)

Overall I say great job. I was able to use it in my current OpenAL test project and it worked as expected! No problems or crashes and especially no memory leaks whatsoever! Great work! What are your plans on public use? I could definitly use this for our projects [smile] I could not think of any improvements or additions you could do. It's something that is simple and works.

- Drew
cozman
cozman
Thanks for testing it on so many compilers, so far I'd only tested it on g++, but I'm glad it works on VC7. It doesn't suprise me it doesn't work on VC6, but I'm curious what errors you get, I can only assume it has to do with templates (hopefully they have a working implementation of auto_ptr?)

Feel free to use it, it's just something I threw together while I was frustrated by the fact I was going to probably have to use singletons :)
Drew_Benton
Drew_Benton
Awesome! You will receive credit of course [smile].

Deleting intermediate files and output files for project 'singleton test - Win32 Debug'.--------------------Configuration: singleton test - Win32 Debug--------------------Compiling...StdAfx.cppCompiling...singleton test.cppG:\Visual Studio 6 Projects\singleton test\singleton test.cpp(40) : error C2059: syntax error : 'constant'G:\Visual Studio 6 Projects\singleton test\singleton test.cpp(40) : error C2063: 'instance_' : not a functionG:\Visual Studio 6 Projects\singleton test\singleton test.cpp(40) : error C2040: 'instance_' : 'class std::auto_ptr<_Ty> (void)' differs in levels of indirection from 'class std::auto_ptr<_Ty>'G:\Visual Studio 6 Projects\singleton test\singleton test.cpp(42) : error C2954: template definitions cannot nestError executing cl.exe.singleton test.exe - 4 error(s), 0 warning(s)


The problem it is having is with:
template<class T> std::auto_ptr<T> Singleton<T>::instance_(0);template<class T>Singleton<T>::~Singleton() { }


This just shows how outdated VC6's template and stl is. It's nothing with your code, but theirs. VS6 was released before C++ had the final standards done, so this is why.

- Drew

[edit] spelling

[Edited by - Drew_Benton on February 18, 2005 12:05:43 AM]
cozman
cozman
Yeah, I figured, I know all too well how difficult it is to support VC6, I had an academic copy a few years ago, but by the time I released any code to the public I was using VC7. VC6 users made up at 80% of my emails.. I wrote a few workarounds, but eventually just told them to use a compliant compiler :)
Drew_Benton
Drew_Benton
Quote:
Original post by cozman
Yeah, I figured, I know all too well how difficult it is to support VC6, I had an academic copy a few years ago, but by the time I released any code to the public I was using VC7. VC6 users made up at 80% of my emails.. I wrote a few workarounds, but eventually just told them to use a compliant compiler :)


[lol] Yea I know what you mean. I never noticed how bad VS6 was with STL and templates until I actually tried using them [lol]. However, I really hate how the VS7 does the MFC editing, so either I have to learn how to use it again or just use 6 for MFC then update the project files. That's why I keep my 6 around. Not only that, it's realyl easy to get a project up and running. VS7 tekas twice as long with all those dialogs.
desertcube
desertcube
I have used auto_ptr for my singletons and have never had a problem (I use mmgr to make sure that there are no memory leaks.)
The only thing I would suggest is to make your singleton non-copyable, I just use the non_copyable class from boost.
Here's my implementation (previously posted in this thread)
#include <memory>class non_copyable{protected:	non_copyable() {}	~non_copyable() {}private:	non_copyable(const non_copyable &);	non_copyable & operator=(const non_copyable &);};template <class T>class singleton : non_copyable{public:	static T * Instance()	{		if (!_object.get()) //Not yet created			_object = std::auto_ptr<T>(new T);		return _object.get();	}protected:	singleton() {}	virtual ~singleton() {}	static std::auto_ptr<T> _object; //auto_ptr ensures T is deleted at end};template <class T>std::auto_ptr<T> singleton<T>::_object; //Initilize static variable


Also, I agree with how crap VC6 is, but it is pre standard (and don't it show it!) VC6 actually let me get away with using std::auto_ptr in a std::vector!!
me22
me22
Using auto_ptrs in STL containers was actually legal back in '97 ( reference: http://www.gotw.ca/gotw/025.htm ), although not safe.
dmikesell
dmikesell
Quote:
Original post by petewood
Are people really still using Singletons?

Just Create One.


I like the fact that I can access an object without coupling it unnecessarily to intermediate objects. If a low level object needs to grab something out of the system configuration, I'd rather it go through a Singleton or static class than pass the config object down through several layers of method calls.
andrewo
andrewo
Quote:
Original post by petewood
Are people really still using Singletons?

Just Create One.


Why is it that every time someone brings up the singleton design pattern, someone has to derail the thread into a ridiculous debate over the design implications of using them?

The original poster was simply asking for help in developing his Singleton class - the usefulness and debate over the singleton design pattern are irrelevant.
Conner McCloud
Conner McCloud
Quote:
Original post by petewood
Are people really still using Singletons?

Just Create One.

While I don't use singletons myself, I don't see how JCO is an improvement. Rather than have a concrete idea of a singleton, he just throws it into a globaly available structure. Seems like it just increases the responsibilities of that system class, which he specifically argues against at the begining.

An alternative to singletons? Yes. A general replacement? No.

CM
bkt
bkt
Just wondering why you would wish to do this anyway? I'm not 100% positive but isn't auto_ptr<> a type of memory managed/safe pointer (wouldn't know; I have my own object do that already)? All you need to make sure is that you couple every "BaseClass::Create()" with "BaseClass::Destroy()" for Singletons; they're only made to have one instance anyway. How would you be leaking memory?
-John "bKT" Bellone [homepage] [[email=j.bellone@flipsidesoftware.com]email[/email]]
Qw3r7yU10p!
Qw3r7yU10p!
Quote:
Original post by andrewo
Quote:
Original post by petewood
Are people really still using Singletons?

Just Create One.


Why is it that every time someone brings up the singleton design pattern, someone has to derail the thread into a ridiculous debate over the design implications of using them?

The original poster was simply asking for help in developing his Singleton class - the usefulness and debate over the singleton design pattern are irrelevant.


Okay, sorry. I've started a separate thread here.

However, I would say, if nobody really uses singletons anymore then developing a safe singleton becomes an academic exercise.
KorbenDallas
KorbenDallas
Quote:
Original post by bkt
Just wondering why you would wish to do this anyway? I'm not 100% positive but isn't auto_ptr<> a type of memory managed/safe pointer (wouldn't know; I have my own object do that already)? All you need to make sure is that you couple every "BaseClass::Create()" with "BaseClass::Destroy()" for Singletons; they're only made to have one instance anyway. How would you be leaking memory?

Exactly, seems like an awfull lot of code, while 5 or 6 lines of code in every singleton class will do just as well. Plus, this is a kind of nasty solution, here you can at least attempt to create an instance, and will only run in to trouble at run-time, while with a singleton, you'll see it instantly at compile-time.
cozman
cozman
I'm actually trying to avoid using singletons, as I agree they aren't great. However, I do have a log, which should be globally accessible.

edit: Just noticed the other thread :)
bkt
bkt
I don't really see why they aren't great to use; it's a hell of a lot better than using C-type global pointer system of operations. If you're going to use this method std::auto_ptr then you're also depending your code on the STL (which doesn't mean it's bad...) when it's really avoidable. Just my two cents; I use Singleton objects for things that would normally only be used once throughout the code assigned to them, i.e.: Log system, Memory Manager, Game Kernel, and Globals wrapper.

[Edited by - bkt on February 19, 2005 9:16:19 AM]
-John "bKT" Bellone [homepage] [[email=j.bellone@flipsidesoftware.com]email[/email]]

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.