gpt4 book ai didi

c++ - unique_ptr 成员,私有(private)复制构造函数与移动构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:55:01 30 4
gpt4 key购买 nike

给定多个派生类的基类,目标是创建一个包装类,允许 STL 容器查看具有基接口(interface)的对象,尽管实际上可能会将不同的派生类添加到容器中。 (参见 Retrieve data from heterogeneous std::list)。

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

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());
}

This does not compile with g++ 4.7.2 .

现在,为了使用 BaseWrapper,我可以像这样实现一个公共(public)移动构造函数:

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

And this works fine .但是,如果我将其设为私有(private),it will not compile .

但是,我发现不是上面的,I can instead define a private "copy" constructor (当然公开也行):

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

有人能告诉我这是否可行,为什么或为什么不可行?如果它应该工作,为什么我不能将移动构造函数设为私有(private)?

可以关注this link以更完整的方式说明上述内容的玩具程序。

最佳答案

[删除了错误的诊断]

这实际上是在 gcc 4.8 上编译的。似乎 gcc 4.7 将 BaseWrapper (const Base &) 作为复制构造函数(实际上不是),并隐式删除移动构造函数(如果它确实是复制构造函数,这将是预期的行为) .

关于c++ - unique_ptr 成员,私有(private)复制构造函数与移动构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15821535/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com