![](/img/trans.png)
[英]Why doesn't this use of emplace_back with deleted copy constructor work?
[英]Why does vector<T>::emplace_back, such that T has a deleted copy constructor, fail to compile?
我无法编译以下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(...)
是如何导致复制构造函数被调用的。
std::vector::emplace_back
要求std::vector::emplace_back
的类型为EmplaceConstructible
以及MoveInsertable
。 由于您删除了复制构造函数并且没有自己定义移动构造函数,因此Thing
不满足第二个要求。 相反, std::list::emplace_back
只要求列表类型为EmplaceConstructible
。
它有移动构造函数时有效:
#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
的类型要求可以提供更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.