unique_ptr成员,私有复制构造函数与移动构造函数 [英] unique_ptr member, private copy constructor versus move constructor

查看:1014
本文介绍了unique_ptr成员,私有复制构造函数与移动构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定多个派生类的基类,目标是创建一个包装类,它允许STL容器查看带有基本接口的对象,尽管不同的派生类实际上可以添加到容器中。 (请参见从异质std :: list检索数据)。

Given a base class for multiple derived class, the goal was to create a wrapper class that allowed an STL container to see objects with the base interface, event though different derived classes may actually be added to the container. (See Retrieve data from heterogeneous std::list).

经过一些修改,我想出了一个新的派生类,它是一个 unique_ptr 到基类的包装器。但是,移动构造函数让我困惑。

After some tinkering, I came up with a new derived class that was a wrapper around a unique_ptr to the base class. However, the move constructor has me confused.

class Base {
    friend class BaseWrapper;
    virtual Base * clone () const = 0;
public:
    virtual ~Base () {}
    //... public interface
};

class Derived : public Base {
    //... specific members for derived class
    Base * clone () const { return new Derived(*this); }
public:
    //... implement public interface
};

class BaseWrapper : public Base {
    std::unique_ptr<Base> ptr_;
    Base * clone () const { return ptr_->clone(); }
public:
    BaseWrapper (const Base &b) : ptr_(b.clone()) {}
    //... implement public interface by forwarding to ptr_
};

typedef std::list<BaseWrapper> BaseList;

int main () {
    BaseList l;
    l.push_back(Derived());
}

这不能用g ++ 4.7.2编译。

This does not compile with g++ 4.7.2.

现在,为了使用 BaseWrapper ,我可以像这样实现一个public move构造函数:

Now, in order to use BaseWrapper, I can implement a public move constructor like this:

    BaseWrapper (BaseWrapper &&bw) { ptr_.swap(bw.ptr_); }

这工作很好。但是,如果我将其设为不公开,将无法编译

And this works fine. But, if I make it private, it will not compile.

但是,我发现我可以改为定义一个私有的复制构造函数,而不是上面的它的public也工作,当然):

However, I found that instead of the above, I can instead define a private "copy" constructor (making it public also works, of course):

    BaseWrapper (BaseWrapper &bw) { ptr_.swap(bw.ptr_); }

有人能告诉我这是否应该工作,为什么?如果它应该工作,为什么我不能使移动构造函数私有?

Could someone tell me if this was supposed to work, and why or why not? If it is supposed to work, why can I not make the move constructor private?

您可以按照

You can follow this link to the toy program illustrating the above in a more complete way.

推荐答案

这实际上是编译gcc 4.8。看起来像gcc 4.7将 BaseWrapper(const Base&)作为复制构造函数(实际上不是),并隐式删除move构造函数它确实是一个复制构造函数)。

That actually compiles on gcc 4.8. It seems like gcc 4.7 takes BaseWrapper (const Base &) as a copy constructor(which is actually not), and implicitly deletes the move constructor(which would be expected behaviour if it were indeed a copy constructor).

这篇关于unique_ptr成员,私有复制构造函数与移动构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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