Można też dokonać konstruktora kopii prywatnej, jak również z nowym lub C++ 11 składni można jednoznacznie powiedzieć, że kompilator nie skopiować go i uczynić z domyślnego konstruktora prywatny coś takiego:
struct NonCopyable {
NonCopyable & operator=(const NonCopyable&) = delete;
NonCopyable(const NonCopyable&) = delete;
NonCopyable() = default;
};
class A : NonCopyable {
public:
static std::shared_ptr<A> newA()
{
// Some code, logging, ...
return std::make_shared<A>();
}
private:
A() {} // Default constructor
};
C++ 03 droga była zazwyczaj coś takiego:
class A {
public:
static A* newA()
{
// Some code, logging, ...
return new A();
}
private:
A() {} // no outsider default constructor
A(const A& rhs); // no copy
A& operator=(const A& rhs); // no assignment
};
int main()
{
A x; // C2248
A y(x); // C2248
x = y; // C2248
A* p = A::newA(); // OK
std::cin.get();
return 0;
}
Singletons są złe. Zobacz tutaj: http://programmers.stackexchange.com/questions/40373/so-singletons-are-bad-then-what –
@Truth: To nie wygląda jak singleton. –
@OliCharlesworth: Fabryka, która zwraca instancję samego siebie i uniemożliwia innym tworzenie jej? Wygląda niebezpiecznie blisko. –