I have this code that doesn\'t work, but I think the intent is clear:
testmakeshared.cpp
#include
class A {
public:
stat
There's a more hairy and interesting problem that happens when you have two strictly related classes A and B that work together.
Say A is the "master class" and B its "slave". If you want to restrict instantiation of B only to A, you'd make B's constructor private, and friend B to A like this
class B
{
public:
// B your methods...
private:
B();
friend class A;
};
Unfortunately calling std::make_shared()
from a method of A
will make the compiler complain about B::B()
being private.
My solution to this is to create a public Pass
dummy class (just like nullptr_t
) inside B
that has private constructor and is friend with A
and make B
's constructor public and add Pass
to its arguments, like this.
class B
{
public:
class Pass
{
Pass() {}
friend class A;
};
B(Pass, int someArgument)
{
}
};
class A
{
public:
A()
{
// This is valid
auto ptr = std::make_shared(B::Pass(), 42);
}
};
class C
{
public:
C()
{
// This is not
auto ptr = std::make_shared(B::Pass(), 42);
}
};