c – std :: vector emplace_back()用于非复制可构建对象

前端之家收集整理的这篇文章主要介绍了c – std :: vector emplace_back()用于非复制可构建对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
考虑到这个来自 en.cppreference.com的关于std :: vector :: emplace_back的引用

“Appends a new element to the end of the container. The element is
constructed in-place,i.e. no copy or move operations are performed.
The constructor of the element is called with exactly the same
arguments that are supplied to the function.”

以下示例:

#include <vector>
struct A
{
    A(int){}
    A(A const&) = delete;
};

int main()
{
    std::vector<A> vec;
    vec.emplace_back(1);

    return 0;
}

在线vec.emplace_back(1); Visual Studio 2013 / GCC报告:

error C2280: ‘A::A(const A &)’ : attempting to reference a deleted function

error: use of deleted function ‘A::A(const A&)’

错误是否正确?你能解释一下为什么吗

解决方法

C 11 23.2.1表101规定:

Expression: a.emplace_back(args)

Return type: void

Operation semantics: Appends an object of type T constructed with std::forward<Args>(args).... Requires: T shall be EmplaceConstructible into X from args. For vector,T shall also be MoveInsertable into X.

您的A不符合MoveInsertable要求,因为您没有移动构造函数,只有一个已删除的副本构造函数.与std :: vector,it works之外的容器.

原文链接:https://www.f2er.com/c/112346.html

猜你在找的C&C++相关文章