Implementation of Singleton?

I need one copy of a class object throughout my program so I decided on a singleton. I used the basic design of:
1
2
3
4
5
6
7
8
9
10
11
class ImageManager{
public:
static ImageManager &GetInstance(){
		static ImageManager imgr;
		return imgr;
	}
private:
ImageManager(){};
ImageManager(const ImageManager&);
ImageManager& operator = (const ImageManager&);
};


From what I've read, this is ok. How do I actually create the ImageManager object though? For instance:
1
2
3
4
class Board{ImageManager imgr;}
Board(){
imgr = imgr.GetInstance();
}

returns the error c2248 that GetInstance() is inaccesible. How do I create my singleton object from the singleton class?
The point of a Singleton is you cannot create one on the fly, and you can't copy one. That's why the constructor if private and the copy constructor and assignment operators are not defined.

The GetInstance class returns a reference to an ImageManager. You can assign an ImageManager reference. So change Board::imgr from type ImageManager to type ImageManager&.
Do you need an object?

Wouldn't something along these lines suffice?

image_manager.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#ifndef IMAGE_MANAGER_H_WAS_ALREADY_INCLUDED
#define IMAGE_MANAGER_H_WAS_ALREADY_INCLUDED

#include <string>

struct image ;

namespace image_manager
{
    std::size_t size() ;

    const image& get( std::string name ) ;

    void add( std::string name, const image& image ) ;

    // etc
}

#endif // IMAGE_MANAGER_H_WAS_ALREADY_INCLUDED 


image_manager.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include "image_manager.h"
#include "image.h"
#include <map>

namespace image_manager
{
    namespace // internal linkage, programmatically not visible outside
    {
        std::map< std::string, image > images ;

        // other image_manager data

        // image_manager helper functions
    }


    // image_manager public interface (external linkage)

    std::size_t size() { return images.size() ; }

    const image& get( std::string name )
    {
        const auto iter = images.find(name) ;
        if( iter == images.end() ) throw "not found" ;
        else return iter->second ;
    }

    void add( std::string name, const image& image ) { images[name] = image ; }

    // etc
}


board.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "image_manager.h"
#include "image.h"

struct board
{
    void foo()
    {
        image_manager::add( "default", image( /*.... */ ) ) ;

        // ...
    }

    void bar( std::string image_name )
    {
        const image& img = image_manager::get(image_name) ;

        // use img
    }
};
Topic archived. No new replies allowed.