今天遇到了个c++编译错误,代码如下:

#include <bits/stdc++.h>
#include <condition_variable>
using namespace std;
vector<condition_variable> v;
int main()
{
    v.emplace_back();
    return 0;
}

然后报错是

/usr/include/c++/10/bits/stl_uninitialized.h: In instantiation of ‘_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = std::move_iterator<std::condition_variable*>; _ForwardIterator = std::condition_variable*]’:
/usr/include/c++/10/bits/stl_uninitialized.h:325:37:   required from ‘_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = std::move_iterator<std::condition_variable*>; _ForwardIterator = std::condition_variable*; _Tp = std::condition_variable]’
/usr/include/c++/10/bits/stl_uninitialized.h:347:2:   required from ‘_ForwardIterator std::__uninitialized_move_if_noexcept_a(_InputIterator, _InputIterator, _ForwardIterator, _Allocator&) [with _InputIterator = std::condition_variable*; _ForwardIterator = std::condition_variable*; _Allocator = std::allocator<std::condition_variable>]’
/usr/include/c++/10/bits/vector.tcc:474:3:   required from ‘void std::vector<_Tp, _Alloc>::_M_realloc_insert(std::vector<_Tp, _Alloc>::iterator, _Args&& ...) [with _Args = {}; _Tp = std::condition_variable; _Alloc = std::allocator<std::condition_variable>; std::vector<_Tp, _Alloc>::iterator = std::vector<std::condition_variable>::iterator]’
/usr/include/c++/10/bits/vector.tcc:121:21:   required from ‘void std::vector<_Tp, _Alloc>::emplace_back(_Args&& ...) [with _Args = {}; _Tp = std::condition_variable; _Alloc = std::allocator<std::condition_variable>]’
test.cpp:7:20:   required from here
/usr/include/c++/10/bits/stl_uninitialized.h:137:72: error: static assertion failed: result type must be constructible from value type of input range
  137 |       static_assert(is_constructible<_ValueType2, decltype(*__first)>::value,
      |                         

研究了半天,终于搞明白了。我之前只知道condition_variable不可拷贝构造,原来condition_variable同样不可以移动构造!!因此是不能把condition_variable放入容器来进行管理的。但可以用容器来管理指向cv的shared_ptr或者unique_ptr,这样就好了

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注