Abhijit Abhijit - 5 months ago 31
C++ Question

Friend function is unable to construct a unique pointer of the class

I have a certain design strategy where the constructor of my class is private and can only be constructed by friends of the class. Inside the friend function, I am trying to create a unique_pointer of my class using

but it doesn't compile. My VC12 compiler complains

c:\program files (x86)\microsoft visual studio
12.0\vc\include\memory(1639): error C2248: 'Spam::Spam' : cannot access private member declared in class 'Spam'

The relevant code which fails during compilation is as follows

#include <memory>
class Spam {
friend void Foo();

Spam(int mem) :mem(mem) {}
int mem;
void Foo() {
std::unique_ptr<Spam> spam = std::make_unique<Spam>(10);

Why am I not able to compile?

Answer Source

In your case the function make_unique is trying to create an instance of Spam and that function is not a friend. Calling a non-friend function from inside a friend function does not imbue the non-friend function with friend status.

To solve this you can write in Foo:

std::unique_ptr<Spam> spam(new Spam(10));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download