Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 633
Vero Avatar asked Oct 18 '25 03:10

Vero


1 Answers

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. 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;
}
like image 195
Lala5th Avatar answered Oct 20 '25 18:10

Lala5th