可变参数构造函数优先于用户提供的移动构造函数,除非默认
Variadic constructor is being preferred to the user provided move constructor except when defaulted
考虑以下代码片段,其中我有一个仅移动Wrapper
对象,该对象将参数转发到构造的基础数据。现在,如果我在另一个仅移动类(在本例中SomeObject
)中使用此Wrapper
对象,除非默认使用 SomeObject
的移动构造函数,否则它不会编译。
#include <utility>
template <typename T> class Wrapper {
public:
template <typename... Args>
Wrapper(Args &&... args) : _data{std::forward<Args>(args)...} {}
Wrapper(const Wrapper &) = delete;
Wrapper(Wrapper &&other) : _data(std::move(other)) {}
T &get() const { return _data; }
protected:
T _data;
};
struct SomeObject {
SomeObject(const SomeObject &) = delete;
SomeObject(SomeObject &&other) : x(std::move(other.x)) {}
//SomeObject(SomeObject &&other) = default; // this works!
SomeObject(int val) : x(val) {}
Wrapper<int> x;
};
int main() {
SomeObject obj(10);
return 0;
}
使用 gcc 6.3,我们得到:
test.cpp: In instantiation of ‘Wrapper<T>::Wrapper(Wrapper<T>&&) [with T = int]’:
test.cpp:20:56: required from here
test.cpp:10:52: error: cannot convert ‘std::remove_reference<Wrapper<int>&>::type {aka Wrapper<int>}’ to ‘int’ in initialization
Wrapper(Wrapper &&other) : _data(std::move(other)) {}
^
我在这里缺少什么吗?用户提供的 move 构造函数SomeObject
与编译器默认时定义的构造函数不同吗?
我唯一能找到的接近这个答案的是这个答案,但我觉得这是一个不同的情况,因为我的 SomeObject
移动构造函数没有传递const
类型。
这是
意料之中的。查看您的代码:
Wrapper(Wrapper &&other) : _data(std::move(other)) {}
T _data;
在您的情况下,T 是 int。您想如何从Wrapper<int>
初始化int
?
相关文章:
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- 为什么调用复制构造函数而不是移动构造函数?
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 具有已删除移动和复制构造函数的类的就地构造
- 移动构造函数和右值引用
- 使用移动调用对等构造函数unique_ptr默认构造函数
- 为什么 std::memmove 中联合的默认非平凡移动构造函数C++?
- 具有专用化的模板类中的可靠条件复制和移动构造函数
- 构造函数采用std::string_view与std::string并移动
- C++:为什么不调用移动构造函数?
- 了解构造函数在移动、复制、赋值语义中的行为
- 没有移动的构造函数移动课程
- 引用绑定和复制构造函数/移动构造函数
- 构造函数移动
- C++ 向量实现 - 移动构造函数 - 移动与前进
- 我真的必须取消移动构造函数/移动结构中的所有成员还是只是指针
- 将类(没有默认构造函数)移动到另一个类的move构造函数中