【发布时间】:2017-02-20 15:27:42
【问题描述】:
拥有constexpr 移动构造函数有意义吗?
例如,考虑以下情况:
#include <array>
class C
{
public:
constexpr C(std::array<int, 3> ar) : m_ar{ar} {}
constexpr C(C&& other) : m_ar{std::move(other.m_ar)} { }
private:
std::array<int, 3> m_ar;
};
int main()
{
constexpr C c1 {{{1, 2, 3}}};
constexpr C c2{std::move(c1)};
return 0;
}
这不会编译,因为尽管在 c1 上调用了 std::move,编译器推断它需要使用(隐式删除的)复制构造函数,而不是移动构造函数。我不知道为什么。
但如果我从c1 中删除constexpr,那么constexpr 移动构造函数将无法使用它。
有没有办法让它工作?或者这是 constexpr 移动构造函数的一个坏例子,但是有很好的例子吗?或者,使用constexpr 移动构造函数总是错误的吗?
【问题讨论】:
-
使用
constexpr C(const C&& other),它从 C++14 开始编译。 -
@Jarod42 但它实际上可能不会移动任何东西,因为您无法从 const 对象移动。它只是一个不必要的复杂复制构造函数。
-
@Jarod42 嗯。确实如此。怎么会?我预计
std::move(other.m_ar)会失败,因为other是const C&&(因为它可以编译,我希望它确实 移动other.m_ar,除非它做了一些偷偷摸摸的事情,例如复制other.m_ar而是)。
标签: c++ c++11 constexpr move-constructor