[英]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.