"Jeremie" <je*******@qqpart.com> wrote...
class A
{
<..>
};
const A& GetA()
{
static A a;
return a;
}
is the function GetA() safe in a multi-threaded application (one and
only one A is created) ? I suppose "threads" are not part of c++, but
what about the "common implementation" ?
Please ask about "common implementation" in comp.programming.threads.
C++ does not define anything related to threads and therefore there are
no guarantees one way or the other. That's probably why C++ compiler
implementers do not concern themselves with threading issues. At least
I wouldn't if I were to implement a C++ compiler.
As far as I understand threading, access to a singleton has to be made
safe (using available threading means, like critical sections, mutexes,
etc.) otherwise you run in all kinds of problems when two threads try
to simultaneously change the object or two others try to use the object's
value that can be half-way updated by the other two threads... The fact
that 'A' is declared const doesn't matter. You can still have "mutable"
data in A, or static members that are not affected by constness of any
object of that class.
Of course, if you can make sure that no clients of 'GetA' try to cast
away the constness of it and change it _and_ that no A object has any
mutable data that can change _and_ class A doesn't have any static data
members that also can change at any point, then yes, it's safe, I guess.
But can you really make sure that all those conditions are met?
Victor