在仅移动类型派生的类中定义析构函数,当使用std :: vector的emplace_back或push_back创建时,会产生编译时错误

问题描述 投票:6回答:2

从以下代码中删除注释会导致编译时错误。似乎在派生类中定义析构函数会导致复制构造函数在emplace_back中被调用

#include <vector>

struct A
{
    A() = default;
    A( A& ) = delete;
    A& operator=( A& ) = delete;
    A( A&& ) = default;
    A& operator=( A&& ) = default;
    ~A(){};
};

struct B : public A
{
    using A::A;
    //~B() = default; //ERROR
};

int main()
{
    std::vector< B > list;
    for( int ii = 0; ii < 3; ii++ ) { list.emplace_back(); }
    return 0;
}

错误是:

In file included from /usr/include/c++/5/vector:62:0,
                 from a.cpp:1:
/usr/include/c++/5/bits/stl_construct.h: In instantiation of ‘void std::_Construct(_T1*, _Args&& ...) [with _T1 = B; _Args = {B}]’:
/usr/include/c++/5/bits/stl_uninitialized.h:75:18:   required from ‘static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<B*>; _ForwardIterator = B*; bool _TrivialValueTypes = false]’
/usr/include/c++/5/bits/stl_uninitialized.h:126:15:   required from ‘_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<B*>; _ForwardIterator = B*]’
/usr/include/c++/5/bits/stl_uninitialized.h:281:37:   required from ‘_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = std::move_iterator<B*>; _ForwardIterator = B*; _Tp = B]’
/usr/include/c++/5/bits/stl_uninitialized.h:303:2:   required from ‘_ForwardIterator std::__uninitialized_move_if_noexcept_a(_InputIterator, _InputIterator, _ForwardIterator, _Allocator&) [with _InputIterator = B*; _ForwardIterator = B*; _Allocator = std::allocator<B>]’
/usr/include/c++/5/bits/vector.tcc:422:8:   required from ‘void std::vector<_Tp, _Alloc>::_M_emplace_back_aux(_Args&& ...) [with _Args = {}; _Tp = B; _Alloc = std::allocator<B>]’
/usr/include/c++/5/bits/vector.tcc:101:23:   required from ‘void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = {}; _Tp = B; _Alloc = std::allocator<B>]’
a.cpp:24:57:   required from here
/usr/include/c++/5/bits/stl_construct.h:75:7: error: invalid initialization of non-const reference of type ‘B&’ from an rvalue of type ‘B’
     { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }
       ^
a.cpp:15:8: note:   initializing argument 1 of ‘B::B(B&)’
 struct B : public A
        ^

我正在使用像A这样的基类来管理HANDLE,并且主要是为了调试目的而在派生类中定义析构函数。目前,我在向量中使用智能指针来避免此问题。

我想知道是什么原因造成的,以及如何通过更改代码或使用更合适的容器来解决此问题。任何帮助表示赞赏。

编辑:我正在使用g++ -std=c++11 g ++版本g++ (Ubuntu 5.4.0-6ubuntu1~16.04.11) 5.4.0 20160609

进行编译
c++ c++11 stdvector move-semantics
2个回答
10
投票

使用static_assert验证对CopyConstructible和MoveConstructible

的期望:

1
投票

std::vector添加任何内容可能会导致整个向量的重新分配。为了使此课程成功,类需要提供以下任一方法:

  • 复制构造函数
© www.soinside.com 2019 - 2024. All rights reserved.