为什么vector <t> :: emplace_back,这样T有一个删除的拷贝构造函数,无法编译?

时间:2017-07-01 16:11:29

标签: c++ back emplace

我无法编译以下dont_compile函数。我不明白为什么它不起作用。但是,它确实适用于list

class Thing {
public:
    Thing() {}
    Thing(const Thing &) = delete;
};

int dont_compile(int argc, char ** argv)
{
    std::vector<Thing> v;
    v.emplace_back();

    return 0;
}

int compiles(int argc, char ** argv)
{
    std::list<Thing> v;
    v.emplace_back();

    return 0;
}

以下是编译器的错误。这是一个错误吗?

/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/memory:1752:31: error: call to deleted constructor of 'Thing'
            ::new((void*)__p) _Up(_VSTD::forward<_Args>(__args)...);
                              ^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

... snip ...

note: 'Thing' has been explicitly marked deleted here
        Thing(const Thing &) = delete;

我真的不明白_Up(...)是如何导致调用复制构造函数的。

2 个答案:

答案 0 :(得分:6)

std::vector::emplace_back要求向量的类型为EmplaceConstructible以及MoveInsertable。由于您删除了复制构造函数并且没有自己定义移动构造函数,因此Thing不满足第二个要求。相反,std::list::emplace_back仅要求列表类型为EmplaceConstructible

答案 1 :(得分:5)

当你有移动构造函数时它会起作用:

#include <vector>

class Thing {
public:
    Thing() {}
    Thing(const Thing &) = delete;
    Thing(Thing&&) = default;
};

int main() {
    std::vector<Thing> v;
    v.emplace_back();
    return 0;
}

std::vector::emplace_back的类型要求可以提供更多信息。