简体   繁体   English

为什么矢量 <T> :: \\ templace_back,这样T有一个删除的拷贝构造函数,无法编译?

[英]Why does vector<T>::emplace_back, such that T has a deleted copy constructor, fail to compile?

I cannot compile the following dont_compile function. 我无法编译以下dont_compile函数。 I don't understand why it doesn't work. 我不明白为什么它不起作用。 But, it does work with list . 但是,它确实与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;
}

Here is the error from the compiler. 这是编译器的错误。 Is it a bug? 这是一个错误吗?

/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;

I don't really understand how _Up(...) is causing the copy constructor to be invoked. 我真的不明白_Up(...)是如何导致复制构造函数被调用的。

std::vector::emplace_back requires the type of the vector to be EmplaceConstructible as well as MoveInsertable . std::vector::emplace_back要求std::vector::emplace_back的类型为EmplaceConstructible以及MoveInsertable Since you delete the copy constructor and do not define a move constructor yourself, Thing does not satisfy the second requirement. 由于您删除了复制构造函数并且没有自己定义移动构造函数,因此Thing不满足第二个要求。 In contrast, std::list::emplace_back only requires the list type to be EmplaceConstructible . 相反, std::list::emplace_back只要求列表类型为EmplaceConstructible

It works when you have move constructor: 它有移动构造函数时有效:

#include <vector>

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

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

The type requirements of std::vector::emplace_back can provide more information. std::vector::emplace_back的类型要求可以提供更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM