S
Simon Elliott
Consider the following, incorrect, code:
#pragma hdrstop
#include <condefs.h>
#include <iostream>
#include <conio.h>
class bar
{
private:
operator = (const bar&);
bar(const bar&);
public:
bar(void)
{
cout << "bar: constructor " << std::endl;
}
~bar()
{
cout << "bar: destructor" << std::endl;
}
void Hello(int thing)
{
cout << "bar: say hello " << thing << std::endl;
}
void Goodbye(int thing)
{
cout << "bar: wave goodbye " << thing << std::endl;
}
};
class foo
{
private:
int thing_;
foo();
operator = (const foo&);
foo(const foo&);
static bar &instance()
{
static bar theInstance;
return theInstance;
}
public:
explicit foo(int thing):thing_(thing)
{
cout << "foo: constructor " << thing_ << std::endl;
bar& the_bar = instance();
the_bar.Hello(thing_);
}
~foo()
{
bar& the_bar = instance();
the_bar.Goodbye(thing_);
cout << "foo: destructor " << thing_ << std::endl;
}
};
static foo foo1(1);
static foo foo2(2);
int main(int argc, char **argv)
{
return 0;
}
The output from this is:
foo: constructor 1
bar: constructor
bar: say hello 1
foo: constructor 2
bar: say hello 2
bar: destructor
bar: wave goodbye 2
foo: destructor 2
bar: wave goodbye 1
foo: destructor 1
Which isn't what's required: methods in the static instance of bar are
being called after bar's destructor has been called.
How would I change the code to make sure that the static instance of
bar is destroyed last?
#pragma hdrstop
#include <condefs.h>
#include <iostream>
#include <conio.h>
class bar
{
private:
operator = (const bar&);
bar(const bar&);
public:
bar(void)
{
cout << "bar: constructor " << std::endl;
}
~bar()
{
cout << "bar: destructor" << std::endl;
}
void Hello(int thing)
{
cout << "bar: say hello " << thing << std::endl;
}
void Goodbye(int thing)
{
cout << "bar: wave goodbye " << thing << std::endl;
}
};
class foo
{
private:
int thing_;
foo();
operator = (const foo&);
foo(const foo&);
static bar &instance()
{
static bar theInstance;
return theInstance;
}
public:
explicit foo(int thing):thing_(thing)
{
cout << "foo: constructor " << thing_ << std::endl;
bar& the_bar = instance();
the_bar.Hello(thing_);
}
~foo()
{
bar& the_bar = instance();
the_bar.Goodbye(thing_);
cout << "foo: destructor " << thing_ << std::endl;
}
};
static foo foo1(1);
static foo foo2(2);
int main(int argc, char **argv)
{
return 0;
}
The output from this is:
foo: constructor 1
bar: constructor
bar: say hello 1
foo: constructor 2
bar: say hello 2
bar: destructor
bar: wave goodbye 2
foo: destructor 2
bar: wave goodbye 1
foo: destructor 1
Which isn't what's required: methods in the static instance of bar are
being called after bar's destructor has been called.
How would I change the code to make sure that the static instance of
bar is destroyed last?