gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:36:49 24 4
gpt4 key购买 nike

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com