[英]call to implicitly-deleted copy constructor while using unique_ptr c++ 17
I have following setup:我有以下设置:
class A {
public:
constexpr A() = default;
virtual ~A() = default;
virtual void print() const noexcept = 0;
virtual std::unique_ptr<A> clone() const noexcept = 0;
};
class B : public A {
public:
constexpr B() {};
B(const A& a1, const A& a2) : ptr1(a1.clone()), ptr2(a2.clone()) {}
virtual ~B() = default;
virtual void print() const noexcept override {
std::cout << "In B\n";
}
void printPtrs() const noexcept {
ptr1->print();
ptr2->print();
}
virtual std::unique_ptr<A> clone() const noexcept override {
return std::make_unique<B>(*this);
}
private:
std::unique_ptr<A> ptr1;
std::unique_ptr<A> ptr2;
};
class C : public A {
public:
constexpr C() = default;
virtual ~C() = default;
virtual void print() const noexcept override {
std::cout << "In C\n";
}
virtual std::unique_ptr<A> clone() const noexcept override {
return std::make_unique<C>(*this);
}
};
===== MAIN =============
#include "MyClass.h"
#include <vector>
#include <string>
#include <memory>
using namespace std;
int main()
{
C c;
B b;
B B_container(b, c);
B_container.printPtrs();
return 0;
}
I used the 'clone()' method taking the suggestion from this issue: Abstract class and unique pointer我使用了 'clone()' 方法,采纳了这个问题的建议: Abstract class and unique pointer
I am getting this error: call to implicitly-deleted copy constructor of 'B' I am really struggling with this, I don't understand why this copy ctor being called here?我收到此错误:调用“B”的隐式删除复制构造函数我真的很纠结,我不明白为什么要在这里调用此复制构造函数? Any work around?
有什么解决方法吗?
B::clone
attempts to copy a B
object, but B
is non-copyable due to its std::unique_ptr
members. B::clone
尝试复制B
object,但B
由于其std::unique_ptr
成员而不可复制。
Since you have a constructor that accepts two references to A
objects and clones them, you could use that instead:由于您有一个构造函数接受对
A
对象的两个引用并克隆它们,因此您可以改用它:
virtual std::unique_ptr<A> clone() const noexcept override {
return std::make_unique<B>(*ptr1, *ptr2);
}
This will create a new B
object that holds pointers to copies of the A
objects pointed to by this
object's unique_ptr
members instead of attempting to copy the unique_ptr
s themselves, which you cannot do.这将创建一个新的
B
object,它保存指向this
对象的unique_ptr
成员所指向的A
对象副本的指针,而不是尝试复制unique_ptr
本身,这是您无法做到的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.