Re: Assign Reference to another Referance
cpisz <cpisz@austin.rr.com> kirjutas:
I'll give you a compilable example as
soon as I get VS fixed later today.
Good! Please do so!
class Singleton
{
public:
static Singleton & Instance()
{
if( !m_instance )
{
m_instance = new Singleton();
}
return *m_instance;
}
static void DoStuff()
{
int x = 1 + 1;
}
private:
static Singleton * m_instance;
};
Singleton * Singleton::m_instance = 0;
class Foo
{
public:
Foo(){}
~Foo()
{
Singleton::Instance().DoStuff();
}
};
int main()
{
static Foo foo;
return 0; // Undefined behavior after this line, when program
cleanup occurs!
}
I thought you claimed that the alleged UB manifests itself by a segfault
in Linux. I would like to see such an example. (This code appeared to
cause no segfault in my quick test.)
From the standard:
3.6.3/2: If a function contains a local object of static storage duration
that has been destroyed and the function is called during the destruction
of an object with static storage duration, the program has undefined
behavior if the flow of control passes through the definition of the
previously destroyed local object.
So it seems UB might appear if the static pointer we are discussing has
been destroyed. Now what "destroyed" means for a built-in type like a
pointer? I could not find a clear definition of "destruction", but I
found:
3.8/1: The lifetime of an object of type T ends when:
? if T is a class type with a non-trivial destructor (12.4), the
destructor call starts, or
? the storage which the object occupies is reused or released.
So it appears the lifetime of the static pointer ends only when the
memory is unmapped from the process space by the OS (storage released). I
argue that the pointer cannot be considered "destroyed" before its
lifetime ends, so it is not "destroyed" while any of the program code
still runs, so 3.6.3/2 does not apply, hence no UB in your example.
If you claim otherwise, please back up your statements by relevant quotes
from the standard!
Paavo
PS. I am no big fan of singletons, they just don't have such fundamental
problems as you claim.