moorec's asdf dir #2

In this example, I appear to have just read Exceptional C++ by Herb Sutter. Enjoy:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <memory>

namespace pimpl
{

// An application of the Singleton Pattern that provides the strong guarantee
// and uses the Pimpl idiom to minimize compiler dependencies
class Singleton
{
    struct SingletonImpl;
    std::auto_ptr< SingletonImpl > pimpl_;

    static std::auto_ptr< Singleton > instance_;

    Singleton( const Singleton & );             // not defined
    Singleton & operator=( const Singleton & ); // not defined

    Singleton();

public:

    inline static Singleton & get() {
        if( !instance_.get() ) {
            std::auto_ptr< Singleton > temp( new Singleton() );
            using std::swap;
            swap( instance_, temp );
        }
        return *instance_;
    }

    int i() const;

}; // Singleton
std::auto_ptr< Singleton > Singleton::instance_( 0 );

struct Singleton::SingletonImpl {

    int i;

}; // SingletonImpl

Singleton::Singleton() : pimpl_( new SingletonImpl() ) {
}

int Singleton::i() const {
        return pimpl_->i;
}

} // pimpl


int main()
{
    using namespace pimpl;
    using namespace std;
    cout << Singleton::get().i() << endl;

    return 0;
}
This example appears to be a merge of two others: the pimpl idiom and an exception safety. Here is the non-pimpl singleton, for reference:

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
32
33
34
35
36
37
38
#include <memory>

namespace single
{

// An application of the Singleton Pattern that provides the strong guarantee
class Singleton
{
    static std::auto_ptr< Singleton > instance_;

    Singleton( const Singleton & );             // not defined
    Singleton & operator=( const Singleton & ); // not defined

    Singleton() {}

public:

    inline static Singleton & get() {
        if( !instance_.get() ) {
            std::auto_ptr< Singleton > temp( new Singleton() );
            using std::swap;
            swap( instance_, temp );
        }
        return *instance_;
    }

}; // Singleton
std::auto_ptr< Singleton > Singleton::instance_( 0 );
} // single


int main()
{
    using namespace single;
    Singleton::get();

    return 0;
}
Topic archived. No new replies allowed.