你可以把一个pimpl-class放在一个向量中 [英] Can you put a pimpl-Class inside a vector

查看:146
本文介绍了你可以把一个pimpl-class放在一个向量中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用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;
}

实例: https://ideone.com/HYtPMu

这篇关于你可以把一个pimpl-class放在一个向量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆