Consider the following code where I'd like to delegate the creation of an A
object to a method called make
, in order to allow users of the class to only create instances wrapped in a std::shared_ptr
:
#include <memory>
class A {
private:
A() {}
public:
static std::shared_ptr<A> make() {
return std::make_shared<A>();
}
};
int main() {
std::shared_ptr<A> a = A::make();
return 0;
}
I would have thought that, because make
is a member function, it would be allowed to access the private constructor, but apparently that's not the case. Compiling the program fails with the following message in the source of std::shared_ptr
:
/usr/include/c++/8/ext/new_allocator.h:136:4: error: ‘A::A()’ is private within this context
How can I solve this issue?