mardi 2 février 2016

Move objects from a unique_ptr array to a vector

First I create a unique_ptr array of Foo objects. And then I move the objects to a vector as shown in the code below. But this code does not compile. Another question is since the objects were allocated using the array version of the new operator. What happens if an exception occurs and the program has to terminate early before I move back the objects to the unique_ptr array? In such a situation, the vector vec will destroy its contents using the delete operator, not the array version of the delete operator ? How do we solve this kind of problem?

class Foo
{
public:
  int id;

  Foo(){};
};

int main()
{
  int n = 10;

  std::unique_ptr<Foo []> fooarr(new Foo[n]);

  std::vector<std::unique_ptr<Foo>> vec;

  for( int i=0 ; i<n ; i++ ){
    fooarr[i].id = i;
  }

  for( int i=0 ; i<n ; i++ ){
    vec.push_back( std::move(fooarr[i]) );
  }

  //then move back the Foo objects from vec to fooarr

}

Here is what I got from the compiler.

main.cpp: In function 'int main()': main.cpp:47: error: no matching function for call to 'std::vector >, std::allocator > > >::push_back(Foo)' /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_vector.h:733: note: candidates are: void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = std::unique_ptr >, _Alloc = std::allocator > >] /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../include/c++/4.4.7/bits/stl_vector.h:746: note: void std::vector<_Tp, _Alloc>::push_back(_Tp&&) [with _Tp = std::unique_ptr >, _Alloc = std::allocator > >]

Aucun commentaire:

Enregistrer un commentaire