I have a design problem. In my application, I have a few classes to be managed with std::shared_ptr
. We want to enforce that these classes should be created by our std::shared_ptr
only. Therefore, we thought to do something like:
template <typename T>
class make_sharable_only
{
make_sharable_only();
~make_sharable_only();
public:
template <typename ...Args>
static std::shared_ptr<T> CreateShareInstance(Args ...args)
{
std::shared_ptr<T> ptr;
ptr.reset(new T(args...));
return ptr;
}
};
class A: public make_sharable_only<A>
{
};
void f()
{
auto aPtr = A::CreateShareInstance();
}
But, the problem is that even CreateShareInstance
is not able to create the instance of A. I dont want to create the friend
relationship. Is there a way to define such a base class for this purpose?
Thanks in advance.
I dont want to create the
friend
relationship.
Why not? Why reject a working solution?
If you want some other class to have special access to private/protected members then either it needs to derive from your class (not be a base of your class) or it needs to be a friend of your class.
I assume you meant to have a private constructor in A
.
Also this:
std::shared_ptr<T> ptr;
ptr.reset(new T(args...));
return ptr;
should be:
return make_shared<T>(std::forward<Args>(args)...);
Once you write it like that it's so simple that there's no reason to try and use a base class, just put a factory function on A
, it only takes three lines of code (four to make it a template):
class A {
A() = default;
public:
static std::shared_ptr<A> create() {
return std::make_shared<A>();
}
};
You can't instantiate shared_ptr<make_sharable_only>
because make_sharable_only::~make_sharable_only
is private. You can leave the constructor private and make the destructor public (ok, someone could delete a raw pointer obtained from shared_ptr, but doing that by accidentaly is unlikely).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.