In the following code snippet, g++ compiler outputs the following error:
error: ‘B::B(const string&)’ is private within this context 857 |
{ return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
Commenting out the line where smart pointers are used seem to work. However, I'm not sure why it works for the other cases, and still not work for the smart pointer case.
#include <memory>
#include <iostream>
#include "string"
class A;
class B
{
friend class A;
B(const std::string& dummyString) { std::cout << dummyString << std::endl; }
};
class A
{
public:
A()
{
B b("dummy1");
B* pB1 = new B("dummy2");
std::unique_ptr<B> pB2 = std::make_unique<B>("dummy3");
}
};
int main()
{
A a;
}
The problem is that
make_uniquewhich is supposed to construct an instance ofBis not a friend ofB. Therefore it does not have access toB's private constructor.You can use the following to achieve something similar:
In general it is advised to prefer
make_uniqueto callingnewyourself, and I do not encourage it in any way (see here: Differences between std::make_unique and std::unique_ptr with new).But if you are bound to this specific class hirarchy it will solve your issue.