mardi 26 janvier 2021

why a 2-dimensional vector of auto_ptr in C++ does not work?

I am working on a 2-dimensional vector (vector of vector) to carry some pointers in C++.

std::vector< std::vector<object*> > data;

here object is a class and each entry of data carries a pointer to an object instance. I make it work in C++ but the memory management makes it hard to maintain when I apply it to other code. I did some research and someone suggests using a smart pointer instead. I try the following code

  #include <vector>
  #include <memory>
  using namespace std;
  
  int main(void) {
    vector< int > source = {1,2,3,4,5};
    vector< auto_ptr<int> > co;
    vector< vector< auto_ptr<int> > > all;

    co.push_back( auto_ptr<int>(&source[0]) );
    co.push_back( auto_ptr<int>(&source[2]) );
    co.push_back( auto_ptr<int>(&source[4]) ); // it works well up to here

    all.push_back(co); // but it crashs here
    return 0;
  }

One of the error messages is

C:/msys64/mingw64/include/c++/9.2.0/bits/stl_construct.h:75:7: error: no matching function for call to 'std::auto_ptr::auto_ptr(const std::auto_ptr&)' 75 | { ::new(static_cast<void*>(__p)) _T1(std::forward<_Args>(__args)...); } | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I wonder in what way I could add the vector< auto_ptr<int> > to another vector or list?

Aucun commentaire:

Enregistrer un commentaire