C++ 使用make_与受保护的构造函数共享+;抽象接口
给定一个抽象接口和从该接口派生的实现,其中构造函数受到保护(这些对象的创建只能从类工厂中获得-以实现DI模式),如何在工厂函数中使用make_shared 例如:C++ 使用make_与受保护的构造函数共享+;抽象接口,c++,constructor,protected,visual-c++-2010,make-shared,C++,Constructor,Protected,Visual C++ 2010,Make Shared,给定一个抽象接口和从该接口派生的实现,其中构造函数受到保护(这些对象的创建只能从类工厂中获得-以实现DI模式),如何在工厂函数中使用make_shared 例如: class IInterface { public: virtual void Method() = 0; }; class InterfaceImpl : public IInterface { public: virtual void Method() {} protected:
class IInterface
{
public:
virtual void Method() = 0;
};
class InterfaceImpl : public IInterface
{
public:
virtual void Method() {}
protected:
InterfaceImpl() {}
};
std::shared_ptr<IInterface> Create()
{
std::shared_ptr<IInterface> object = std:: make_shared<InterfaceImpl>();
return object;
}
因此,阅读这里的内容(问题:),我尝试将以下内容放入实现类中:
friend std::shared_ptr<InterfaceImpl> std::make_shared<InterfaceImpl>();
friend std::shared_ptr std::make_shared();
它仍然无法编译。然后我把另一个也放到了界面课上。还是没有快乐。我做错了什么
编辑:用于编译的完整源文件,带有“friend”
#包括
第三类接口
{
公众:
friend std::shared_ptrIInterface>Create();
虚空方法()=0;
};
类接口IMPL:公共接口
{
公众:
虚空方法(){}
受保护的:
friend std::shared_ptrIInterface>Create();
InterfaceImpl(){}
};
std::shared_ptr Create()
{
std::shared_ptr object=std::make_shared();
返回对象;
}
void main()
{
std::shared_ptr i=Create();
}
对于VC10,您链接到的解决方案不起作用-在make\u shared
中不会构造InterfaceImpl
的实例,而是在std::tr1::\u Ref\u count\u obj::\u Ref\u count\u obj(void)
中的内部类型中
在您的情况下,我只是将Create()
函数设置为friend
,而不是使用make\u shared()
:
对于最初的问题,std::make_shared()并没有直接实例化您的类,因此,正如您所发现的,提供对它的友人访问不会产生任何好处。您只需提供对直接使用受保护构造函数的代码的友人访问,如下所示:
friend class std::tr1::_Ref_count_obj<TheClassManagedByTheShared_Ptr>;
friend类std::tr1::\u Ref\u count\u obj;
或者在您的情况下:
friend class std::tr1::_Ref_count_obj<InterfaceImpl>;
friend类std::tr1::\u Ref\u count\u obj;
这适用于VS2010中的Microsoft编译器,但看起来它可能是特定于环境的,因为它不适用于Linux上的gcc。对于gcc,std::tr1命名空间不存在,因此它必须特定于std库的Microsoft实现
我的正常工作环境是英特尔12.1编译器,它似乎有一个根本不检查访问权限的bug,并且在没有任何好友声明的情况下愉快地构建代码 我猜那是VC10?GCC btw没有问题,只要你成为朋友
make_shared()
。这是VS2010,它实际上给出了一个警告(错误-详细信息如下:)。我担心这也不会编译@罗布:嗯,我在发布之前在VC10中测试过。你在用不同的代码测试吗?也许我遗漏了什么。以下是我正在编译的代码(跟进“答案”,因为注释似乎不允许使用代码…!)…@rob:不要发布此类内容的“答案”,而是编辑问题以进行更新。@rob:您的更新仍然使用make_shared()
-尝试从我的答案中复制/粘贴Create()
。与VC2013合作。即使我的班级是模板化的。
class InterfaceImpl : public IInterface {
// ...
protected:
friend std::shared_ptr<IInterface> Create();
InterfaceImpl() {}
};
std::shared_ptr<IInterface> Create() {
return std::shared_ptr<IInterface>(new InterfaceImpl());
}
class InterfaceImpl : public IInterface {
public:
class Key {
friend std::shared_ptr<IInterface> Create();
Key() {}
};
InterfaceImpl(const Key&) {}
};
std::shared_ptr<IInterface> Create() {
std::shared_ptr<IInterface> object =
std::make_shared<InterfaceImpl>(InterfaceImpl::Key());
return object;
}
friend class std::tr1::_Ref_count_obj<TheClassManagedByTheShared_Ptr>;
friend class std::tr1::_Ref_count_obj<InterfaceImpl>;