我在VS2013中遇到以下代码时出错......
class Bob
{
private:
std::vector<std::unique_ptr<UnrelatedClass>> _aVector;
inline Bob(const Bob & other) {};
inline Bob & operator=(const Bob & other) { return *this; };
public:
Bob();
~Bob();
Bob(Bob && o);
};
class Fred
{
friend class Bob;
[... A few functions, Bob never used ...]
};
...通过删除friend class Bob;
编译得很好。这是编译错误吗?我不确定我做错了什么。
错误如下:
c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0(615): error C2248: 'std::unique_ptr<Unrelated,std::default_delete<_Ty>>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<Unrelated,std::default_delete<_Ty>>'
with
[
_Ty=Unrelated
]
c:\program files (x86)\microsoft visual studio 12.0\vc\include\memory(1487) : see declaration of 'std::unique_ptr<Unrelated,std::default_delete<_Ty>>::unique_ptr'
with
[
_Ty=Unrelated
]
c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0(614) : while compiling class template member function 'void std::allocator<_Ty>::construct(_Ty *,const _Ty &)'
with
[
_Ty=std::unique_ptr<Unrelated,std::default_delete<Unrelated>>
]
c:\program files (x86)\microsoft visual studio 12.0\vc\include\xmemory0(752) : see reference to function template instantiation 'void std::allocator<_Ty>::construct(_Ty *,const _Ty &)' being compiled
with
[
_Ty=std::unique_ptr<Unrelated,std::default_delete<Unrelated>>
]
c:\program files (x86)\microsoft visual studio 12.0\vc\include\type_traits(580) : see reference to class template instantiation 'std::allocator<_Ty>' being compiled
with
[
_Ty=std::unique_ptr<Unrelated,std::default_delete<Unrelated>>
]
c:\program files (x86)\microsoft visual studio 12.0\vc\include\vector(650) : see reference to class template instantiation 'std::is_empty<_Alloc>' being compiled
with
[
_Alloc=std::allocator<std::unique_ptr<Unrelated,std::default_delete<Unrelated>>>
]
c:\...\include\bob.h(51) : see reference to class template instantiation 'std::vector<std::unique_ptr<Unrelated,std::default_delete<_Ty>>,std::allocator<std::unique_ptr<_Ty,std::default_delete<_Ty>>>>' being compiled
with
[
_Ty=Unrelated
]
研究让我明白这是复制Bob
时产生的错误。因此,复制std::vector
,因此复制std::unique_ptr
答案 0 :(得分:3)
我找到了解决方案。似乎问题是部分编译器问题,主要是我的错。更新我的编译器会产生一个更好的错误消息,描述使用已删除的函数作为问题的原因。
我将问题追溯到以下一行:
_aVector.push_back(someUniquePtr);
应该是:
_aVector.push_back(std::move(someUniquePtr));
下次我必须更加小心;)