私有化构造函数

有的时候我们希望私有化构造函数,然后要求用户只通过工厂方法访问我们的类型,在 std::enable_shared_from_this 的例子 中就有使用。这个例子是从 cppreference 上面抄来的。但是今天我发现去年 11 月有人修改了网页上的例子,修订记录为 https://en.cppreference.com/mwiki/index.php?title=cpp%2Fmemory%2Fenable_shared_from_this&diff=162885&oldid=153414

后来这个例子又有了新的修订,现在这个例子是:

class Best : public std::enable_shared_from_this<Best>
{
    struct Private{ explicit Private() = default; }; // 这个 explicit 构造函数非常重要
 
public:
    // Constructor is only usable by this class
    Best(Private) {}
 
    // Everyone else has to use this factory function
    // Hence all Best objects will be contained in shared_ptr
    static std::shared_ptr<Best> create()
    {
        return std::make_shared<Best>(Private());
    }
 
    std::shared_ptr<Best> getptr()
    {
        return shared_from_this();
    }
};

构造函数不再私有,调用者能明确看到需要一个私有的标记类,从而对 API 的使用方式会更加清楚。

尤其是 Private 类中的 explicit Private() = default; 非常重要,如果没有这个,使用者可以通过避免明确书写 Private 类型而构造出 Private 类型的对象!这是非常危险的。

int main() {
  Best best({});
}