Reputation: 495
can someone explain me this code?
class S
{
public:
static S& getInstance()
{
static S instance;
return instance;
}
private:
S() {}
S(S const&); // Don't Implement.
void operator=(S const&); // Don't implement
};
What I understood is : getInstance is a static method that will return a reference to the instance, but where is this instance created ? I don't see any new S(); so..
Upvotes: 0
Views: 71
Reputation: 1050
A block-scope entity with static storage duration (in your case the static S instance;
) is initialized the first time control passes through its declaration. Before C++11, this is not thread-safe (however, certain compilers do offer options to enforce thread-safe). As for C++11, the standard states that "If control enters the declaration concurrently while the variable is being initialized, the concurrent execution shall wait for completion of the initialization."
Upvotes: 1