我有一个带有 const 成员的类,它需要移动构造函数和赋值。
我通过以下方式实现它:
struct C
{
const int i;
C(int i) : i{i} {}
C(C && other) noexcept: i{other.i} {}
C & operator=(C && other) noexcept
{
//Do not move from ourselves or all hell will break loose
if (this == &other)
return *this;
//Call our own destructor to clean-up before moving
this->~C();
//Use our own move constructor to do the actual work
new(this) C {std::move(other)};
return *this;
}
//Other stuff here (including the destructor)....
}
Run Code Online (Sandbox Code Playgroud)
这将编译并按预期工作。
问题是这是否是实现这种移动分配的正常方法,还是有一种不那么做作的方法?
我想要一个std:arrayof std::function,但是我要确保该数组的所有元素都已初始化。为此,我构建了一个包装器类,该包装器类将a std::function作为构造参数。
但是,当我直接使用函数(应该在inside的函数)初始化包装器类的数组时,std::function它将无法编译。
这是问题,经过提炼:
#include <functional>
#include <array>
static void f() {}
using F = std::function<void(void)>;
enum { Count = 4 };
struct C
{
//To get a compilation error when some
// elements of the array are not initialized.
C() = delete;
C(F) {}
};
//OK
static const C c {f};
//OK
static const std::array<F,Count> direct
{
F{f},
{f},
f,
f
};
static const std::array<C,Count> wrapper
{
F{f}, //OK
C{f}, //OK
{f}, …Run Code Online (Sandbox Code Playgroud)