c++ - Delete a vector without deleting the array -


i'm trying populate vector of doubles in c++ , pass associated array fortran. i'm having trouble freeing rest of memory associated vector. i'd avoid copying. here's have:

std::vector<double> *vec = new std::vector<double>(); (*vec).push_back(1.0); (*vec).push_back(2.0); *arr = (*vec).data();            //arr goes fortran 

how delete vec while keeping arr intact? there way nullify pointer arr in vec can delete vec?

update

i see didn't give enough information here. couple things:

  1. i'm calling c++ function in fortran using iso_c_binding
  2. i don't know how large vec needs be. vector class looks situation

i might try guillaume's suggestion eventually, now, i'm passing vec fortran , calling c++ function delete once i'm done data

you need rethink program design.

somehow, somewhere, need keep array alive while fortran using it. whatever context you're using access fortran should responsible ownership of array.

class fortran_context {     /*blah blah blah whatever api you're using access fortran*/     void * arr;     std::vector<double> vec; //don't allocate pointer; makes no sense! public:     fortran_context() {         arr = //do whatever necessary setup fortran stuff. i'm assuming         //api has kind of "get_array_pointer" function you'll use.     }      ~fortran_context() {         //do cleanup fortran stuff     }      //if want spend time figuring out robust copy constructor, may.     //personally, suspect it's better delete it, , make object non-copyable.     fortran_context(fortran_context const&) = delete;      std::vector<double> & get_vector() {         return vec;     }      std::vector<double> const& get_vector() const {         return vec;     }      void assign_vector_to_array() {         *arr = vec.data();     }      void do_stuff_with_fortran() {         assign_vector_to_array();         //???     } };  int main() {     fortran_context context;     auto & vec = context.get_vector();     vec.push_back(1.0);     vec.push_back(2.0);     context.do_stuff_with_fortran();     return 0; } //cleanup happens automatically due correct implementation of ~fortran_context() 

i've abstracted lot of because don't know api you're using access fortran, , don't know kind of work you're doing array. is, far, safest way ensure that

  • the vector's allocated memory exists long doing stuff in fortran
  • the memory associated vector cleaned when you're done.

Comments