struct Foo {
int i_;
Foo(int i) :i_(i) { std::cout << "Foo:" << i_ << "\n"; }
~Foo() { std::cout << "~Foo" << i_ << "\n"; }
};
class FooSingleton
{
public:
static std::weak_ptr<Foo> GetInstance()
{
auto tmp = std::atomic_load(&instance);
if (tmp == nullptr) {
std::lock_guard<std::mutex> lock(mutex1);
tmp = std::atomic_load(&instance);
if (tmp == nullptr) {
tmp = std::make_shared<Foo>(2);
std::atomic_store(&instance, tmp);
}
}
return tmp;
}
private:
static std::mutex mutex1;
static std::shared_ptr<Foo> instance;
};
Was reading Double-check locking http://preshing.com/20130930/double-checked-locking-is-fixed-in-cpp11/, but I also need using shared_ptr to own raw pointer.
From documentation I know, that I can't use shared_ptr as template for std::atomic (§29.5 1 in N3290)
Update: my realization seems to be right (although it not elegant) - as it passed code review.Thanks to all!