Friend函数无法构造类的唯一指针 [英] Friend function is unable to construct a unique pointer of the class
问题描述
我有一种确定的设计策略,其中我班的构造函数是私有的,只能由班上的朋友构造。在朋友函数中,我尝试使用 std :: make_unique
创建我的类的unique_pointer,但是无法编译。我的VC12编译器抱怨
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 std::make_unique
but it doesn't compile. My VC12 compiler complains
c:\program files(x86)\Microsoft Visual Studio
12.0\vc\ include\memory(1639):错误C2248: Spam :: Spam:无法访问在 Spam类中声明的私有成员
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 {
public:
friend void Foo();
private:
Spam(int mem) :mem(mem) {}
int mem;
};
void Foo() {
std::unique_ptr<Spam> spam = std::make_unique<Spam>(10);
}
为什么我不能编译?
推荐答案
在您的情况下,函数 make_unique
试图创建 Spam的实例
,该函数不是朋友。从朋友功能内部调用非朋友功能不会使非朋友功能具有朋友状态。
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.
要解决此问题,您可以编写 Foo
:
To solve this you can write in Foo
:
std::unique_ptr<Spam> spam(new Spam(10));
这篇关于Friend函数无法构造类的唯一指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!