考虑到A类,我想将其创建限制为新的.那是
A* a = new A; // Would be allowed.
A a; // Would not be allowed.
Run Code Online (Sandbox Code Playgroud)
怎么可以实现呢?
您可以将构造函数设为私有,并提供static返回动态分配的实例的工厂方法:
class A
{
public:
static A* new_instance() { return new A(); }
private:
A() {}
};
Run Code Online (Sandbox Code Playgroud)
而不是返回原始指针,请考虑返回智能指针:
class A
{
public:
static std::shared_ptr<A> new_instance()
{
return std::make_shared<A>();
}
private:
A() {}
};
Run Code Online (Sandbox Code Playgroud)
一个选项是使构造函数成为私有,并使用静态帮助函数:
class A {
private:
A() {} // Default constructor
A(const A &a); // Copy constructor
public:
static A *create() { return new A; }
};
...
A a; // Won't compile
A *p = A::create(); // Fine
Run Code Online (Sandbox Code Playgroud)
虽然你应该强烈考虑返回智能指针而不是原始指针.