2015-03-03 113 views
0

我有2个类,我想返回一个私有成员对象的引用。unique_ptr:所以我不能再引用已删除的函数

class BB{}; 

class B 
{ 
    std::unique_ptr<BB> b; 
public: 
    const std::unique_ptr<BB>& getBB(){return b;} 
}; 
int main() 
{ 
    B b; 
    std::unique_ptr<BB> x=b.getBB(); 
} 

毫无疑问,在x=b.GetBB(),说 ...can't be referenced. It's a deleted function.

+1

请问您能否发布完整的错误? – RedX 2015-03-03 07:35:16

+0

离开'std :: unique_ptr b;'未初始化的不是默认构造的'BB'使btw,除非你遗漏了'B'的构造函数。 – aruisdante 2015-03-03 07:36:59

回答

3

您要复制初始化unique_ptr在主要发生错误,这是不允许的,因为unique_ptr删除了拷贝构造函数。尝试

const std::unique_ptr<BB>& x = b.getBB(); 
+0

谢谢,它的工作原理,我会从现在开始把它作为一个不断的参考 – user3525475 2015-03-03 07:45:31

相关问题