如何仅在C++中将对象创建限制为指针

lea*_*ing 2 c++ pointers

考虑到A类,我想将其创建限制为新的.那是

A* a = new A; // Would be allowed.
A a;  // Would not be allowed.
Run Code Online (Sandbox Code Playgroud)

怎么可以实现呢?

hmj*_*mjd 8

您可以将构造函数设为私有,并提供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)

  • 考虑返回一个`unique_ptr`.这应该是"默认"智能指针.如果客户需要,可以很容易地从`unique_ptr'构建`shared_ptr`.如果他们不想要它,他们就不需要付钱. (2认同)

Oli*_*rth 5

一个选项是使构造函数成为私有,并使用静态帮助函数:

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)

虽然你应该强烈考虑返回智能指针而不是原始指针.