你可以把一个pimpl-class放在一个向量中 [英] Can you put a pimpl-Class inside a vector
问题描述
我有一个使用PImpl Ideom实现的类:
I have a class implemented using the PImpl Ideom:
class FooImpl {};
class Foo
{
unique_ptr<FooImpl> myImpl;
public:
Foo();
~Foo();
};
现在我想把它放入std :: vector
And now I want to put this into a std::vector
void Bar()
{
vector<Foo> testVec;
testVec.resize(10);
}
但是当我这样做,我得到一个编译器错误/ p>
But when I do that, I get a compiler error (VC++ 2013)
错误C2280:'std :: unique_ptr> :: unique_ptr(const std :: unique_ptr< _Ty,std :: default_delete< _Ty >> &)':尝试引用已删除的函数
error C2280: 'std::unique_ptr>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)' : attempting to reference a deleted function
我遇到与 testVec.emplace_back );
和 testVec.push_back(std :: move(Foo()));
(作为解决方法,使用向量< unique_ptr< Foo>>
似乎工作,但我不明白为什么上面的代码不工作。)
(As a workaround, using vector<unique_ptr<Foo>>
seems to work, but I don't understand why the code above doesn't work.)
工作范例: http:// coliru .stacked-crooked.com / a / b274e1209e47c604
推荐答案
由于 std :: unique_ptr
不可复制,类 Foo
没有有效的复制构造函数。
Since std::unique_ptr
is not copyable, class Foo
does not have a valid copy constructor.
#include <memory>
#include <vector>
class FooImpl {};
class Foo
{
std::unique_ptr<FooImpl> myImpl;
public:
Foo( Foo&& f ) : myImpl( std::move( f.myImpl ) ) {}
Foo(){}
~Foo(){}
};
int main() {
std::vector<Foo> testVec;
testVec.resize(10);
return 0;
}
这篇关于你可以把一个pimpl-class放在一个向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!