首页 > 解决方案 > 创建 std::vector 时,“结果类型必须可以从输入范围的值类型构造”

问题描述

我有一个看起来像这样的班级成员

class Controller {
    protected:
    // other stuff
    std::vector<Task<event_t, stackDepth>> taskHandlers; 

    //some more stuf
}

该类Task是 non-defaultConstructible、non-copyConstructible、non-copyAssignable,但是是 moveConstructible 和 moveAssignable。我能读到的所有东西(特别是std::vector文档)都让我认为这应该编译,但错误列表看起来像这样(此处的完整输出):

/usr/include/c++/9/bits/stl_uninitialized.h:127:72: error: static assertion failed: result type must be constructible from value type of input range
  127 |       static_assert(is_constructible<_ValueType2, decltype(*__first)>::value,
      |                                                                        ^~~~~

使TaskdefaultConstructible 没有帮助。错误指向类的定义Controller。我在 c++17 模式下使用 GCC 9.3.0。我做错什么了吗?

标签: c++vectorcompiler-errorsinitializationmove-semantics

解决方案


鉴于当前信息,我最好的猜测是您以某种方式弄乱了移动构造函数语法 - 仅使用以下示例emplace_back

下面的编译很好,链接到 godbolt

#include <vector>

class X
{
public:
    X(int i) : i_(i){}
    X() = delete;
    X(const X&) = delete;
    X(X&&) = default;//change this to 'delete' will give a similar compiler error
private:
    int i_;
};


int main() { 
    std::vector<X> x;
    x.emplace_back(5);
}

推荐阅读