假设我有一个带有工厂方法的类
class A {
public:
static A* newA()
{
// Some code, logging, ...
return new A();
}
}
是否可以使用new
阻止此类对象的实例化,以便工厂方法是创建对象实例的唯一方法?
答案 0 :(得分:8)
不确定;只需将构造函数设为私有(如果这是一个基类,则受保护):
class A {
public:
static A* newA()
{
// Some code, logging, ...
return new A();
}
private:
A() {} // Default constructor
};
如果需要,您还应该将复制构造函数设置为private / protected。
与往常一样,您应该强烈考虑返回智能指针而不是原始指针,以简化内存管理问题。
答案 1 :(得分:3)
您可能还希望将复制构造函数设置为私有,或者使用新的C ++ 11语法,您可以明确地告诉编译器不要复制它,并使用以下内容将默认构造函数设为私有:
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的方式通常是这样的:
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;
}