c++ - constexpr 移动构造函数是否有意义?

标签 c++ c++11 constexpr move-constructor

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 移动构造函数是否总是错误的?

最佳答案

原则上,移动构造函数可以与非 const 对象一起使用,该对象的生命周期在常量表达式的求值期间开始:

// C++14
constexpr int f() {
    C a(/* ... */);
    C b = std::move(a);
    return 0;
}
constexpr int i = f();

类似的事情可以在 C++11 中完成,例如

constexpr C foo(C&& c) { 
    return std::move(c); 
}

constexpr int f() { 
    return foo(C()), 0; 
}

也就是说,由于常量表达式中使用的所有内容都必须是微不足道的可破坏的,因此移动构造函数的用处相当有限。

关于c++ - constexpr 移动构造函数是否有意义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42348398/

相关文章:

c++ - 如何通过 C 或 C++ API 获取 HDF5 数据集的名称?

c++ - 使用 FFmpeg(或类似工具)将应用程序输出录制为视频

templates - 根据 iterator::value_type 选择函数实现

c++ - 变量如何既是 constexpr 又不是 constexpr?

c++ - 使用constexpr代替#define和#ifdef进行条件编译

c++ - 用户定义类型的非类型模板参数

c++ - 如何将常量放入代码内存

c++ - Microsoft Visual C++ Express 中是否提供创建工作区的选项?

c++ - container.clear() 是否释放/重新分配内部缓冲区?

c++ - 尽管传递了一个右值,为什么我的 move 构造函数没有被调用?