【发布时间】:2019-02-05 03:52:18
【问题描述】:
如何在 g++-6.2.1 中克服/解决此错误
以下代码适用于 g++-7.3.0,但升级编译器对我来说不是一个选项。所以我正在寻找一些 SFINAE 魔法......尝试了一些但到目前为止失败了......
class Base {
public:
Base(std::string str) : s(std::make_shared<std::string>(str)) {}
Base(Base &&base) noexcept { s = std::move(base.s); }
Base &operator=(Base &&i_base_actor) noexcept {
s = std::move(i_base_actor.s);
return *this;
}
virtual ~Base() = default;
private:
std::shared_ptr<std::string> s;
};
// Derived
class Derived : public Base {
public:
Derived() :Base("Derived") {}
~Derived() = default;
};
// Derived1
class Derived1 : public Base {
public:
Derived1(int a) :Base("Derived1") {}
~Derived1() = default;
};
包装函数:
template<typename T, typename... Args>
T construct(Args&&... args) {
return T(std::forward<Args>(args)...);
}
主要:
int main() {
construct<Derived>();
construct<Derived1>(100);
}
g++ 中的错误
optional_params.derived.cc: In instantiation of ‘T construct(Args&& ...) [with T = Derived; Args = {}]’:
optional_params.derived.cc:42:22: required from here
optional_params.derived.cc:37:19: error: use of deleted function ‘Derived::Derived(const Derived&)’
return T(args...);
^
optional_params.derived.cc:21:7: note: ‘Derived::Derived(const Derived&)’ is implicitly deleted because the default definition would be ill-formed:
class Derived : public Base {
^~~~~~~
optional_params.derived.cc:21:7: error: use of deleted function ‘Base::Base(const Base&)’
optional_params.derived.cc:4:7: note: ‘Base::Base(const Base&)’ is implicitly declared as deleted because ‘Base’ declares a move constructor or move assignment operator
class Base {
^~~~
【问题讨论】:
-
默认析构函数有什么原因吗?
-
你应该在
Derived中定义移动构造函数:Derived(Derived&&) = default; -
@Rakete1111 我认为这是强制删除隐式声明的复制构造函数。这只是生产代码的模仿,是由其他人编写的。我所做的只是将签名从 Derived1() 更改为 Derived1(int) 并创建一个包装函数。
-
@SamDaniel 它不会抑制隐式复制构造函数,而是隐式移动构造函数,这就是您的代码失败的原因(您无法复制
Base)。
标签: c++ c++17 variadic-templates move-semantics perfect-forwarding