简体   繁体   English

仅当共享指针时才阻止创建类

[英]Prevent creating a class only if shared pointer

how to prevent people from creating an instance of class, but only create a shared pointer?如何防止人们创建类的实例,而只创建一个共享指针? I am doing something like:我正在做类似的事情:

class OnlyShred
{
public:
    friend std::shared_ptr<OnlyShred> make_shared()
    {
        return std::make_shared<OnlyShred>();  
    };

private:
    OnlyShred() = default;
    OnlyShred(const OnlyShred&) = delete;
    OnlyShred(const OnlyShred&&) = delete;
    OnlyShred& operator=(const OnlyShred&) = delete;
};

Could you please confirm if this is ok?您能否确认这是否可以? And if you can think of a downside doing this?如果你能想到这样做的缺点? The instance can not be copied/moved so this must gurantee that only shared pointer is around when someone uses this class?该实例不能被复制/移动,所以这必须保证当有人使用这个类时只有共享指针存在?

You can use new to allocate the class and then wrap it in std::shared_ptr , since std::make_shared<OnlyShred> will not have access to the constructor.您可以使用new来分配类,然后将其包装在std::shared_ptr中,因为std::make_shared<OnlyShred>将无法访问构造函数。 A way you can do this is:您可以这样做的一种方法是:

class OnlyShred
{
public:

    static std::shared_ptr<OnlyShred> make_shared()
    {
        return std::shared_ptr<OnlyShred>(new OnlyShred);  
    };

private:
    OnlyShred() = default;
    OnlyShred(const OnlyShred&) = delete;
    OnlyShred(const OnlyShred&&) = delete;
    OnlyShred& operator=(const OnlyShred&) = delete;
};

int main() {
    auto ptr = OnlyShred::make_shared();
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM