初始化带有一个元素的向量是否需要复制构造函数?

时间:2015-02-02 16:22:24

标签: c++ c++11 vector move-constructor

以下示例符合clang但在GCC中失败。

Original link

代码:

#include<vector>

struct Foo
{
  Foo() = default;
  Foo(Foo&&) = default;
};

Foo baz(std::vector<Foo> foos);

Foo bar1(Foo&& foo_)
{
  std::vector<Foo> foos{std::move(foo_)};
  return baz(std::move(foos));
}

Foo bar2(Foo&& foo_)
{
  std::vector<Foo> foos;
  foos.push_back(std::move(foo_));
  return baz(std::move(foos));
}

template<typename... Foos>
Foo bar3(Foo&& foo_, Foos&&... foos_)
{
  std::vector<Foo> foos{std::move(foo_), std::forward<Foos>(foos_)...};
  return baz(std::move(foos));
}

void dummy()
{
  Foo f1, f2;
  bar3(std::move(f1), std::move(f2));
}

错误:

In file included from /opt/gcc-4.9.0/include/c++/4.9.0/vector:62:0,

from /tmp/gcc-explorer-compiler11512-1-c5m2m1/example.cpp:1:

/opt/gcc-4.9.0/include/c++/4.9.0/bits/stl_construct.h: In instantiation of 'void std::_Construct(_T1*, _Args&& ...) [with _T1 = Foo; _Args = {const Foo&}]':

/opt/gcc-4.9.0/include/c++/4.9.0/bits/stl_uninitialized.h:75:53: required from 'static _ForwardIterator std::__uninitialized_copy<_TrivialValueTypes>::__uninit_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const Foo*; _ForwardIterator = Foo*; bool _TrivialValueTypes = false]'

/opt/gcc-4.9.0/include/c++/4.9.0/bits/stl_uninitialized.h:125:41: required from '_ForwardIterator std::uninitialized_copy(_InputIterator, _InputIterator, _ForwardIterator) [with _InputIterator = const Foo*; _ForwardIterator = Foo*]'

/opt/gcc-4.9.0/include/c++/4.9.0/bits/stl_uninitialized.h:278:63: required from '_ForwardIterator std::__uninitialized_copy_a(_InputIterator, _InputIterator, _ForwardIterator, std::allocator<_Tp>&) [with _InputIterator = const Foo*; _ForwardIterator = Foo*; _Tp = Foo]'

/opt/gcc-4.9.0/include/c++/4.9.0/bits/stl_vector.h:1286:27: required from 'void std::vector<_Tp, _Alloc>::_M_range_initialize(_ForwardIterator, _ForwardIterator, std::forward_iterator_tag) [with _ForwardIterator = const Foo*; _Tp = Foo; _Alloc = std::allocator<Foo>]'

/opt/gcc-4.9.0/include/c++/4.9.0/bits/stl_vector.h:378:36: required from 'std::vector<_Tp, _Alloc>::vector(std::initializer_list<_Tp>, const allocator_type&) [with _Tp = Foo; _Alloc = std::allocator<Foo>; std::vector<_Tp, _Alloc>::allocator_type = std::allocator<Foo>]'

13 : required from here

/opt/gcc-4.9.0/include/c++/4.9.0/bits/stl_construct.h:75:7: error: use of deleted function 'constexpr Foo::Foo(const Foo&)'

{ ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); }

^

3 : note: 'constexpr Foo::Foo(const Foo&)' is implicitly declared as deleted because 'Foo' declares a move constructor or move assignment operator

struct Foo

^

Compilation failed

如果是GCC中的错误,有人可以为bar3功能建议一个简单的解决方法吗?

1 个答案:

答案 0 :(得分:2)

无法移出initializer_list,因此std::vector的相应构造函数必须复制。这就是你得到错误的原因。 bar2应该编译没有错误。

重复调用push_back的常规模板包扩展技巧应该适用于可变参数版本。