小编Equ*_*ius的帖子

使用常量成员移动类的构造和分配

我有一个带有 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)

这将编译并按预期工作。

问题是这是否是实现这种移动分配的正常方法,还是有一种不那么做作的方法?

c++ c++11

2
推荐指数
1
解决办法
337
查看次数

在std :: array中使用时,无法从std :: function构造一个类

我想要一个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)

c++ initialization c++11 std-function stdarray

2
推荐指数
1
解决办法
58
查看次数

标签 统计

c++ ×2

c++11 ×2

initialization ×1

std-function ×1

stdarray ×1