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. 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With