c++ - std::vector::assign - reallocates the data? -


i working stl library , goal minimize data reallocation cases. wndering,

std::vector::assign(size_type n, const value_type& val)

reallocated data if size not changed or assign new values (for example, using operator=) ?

the stl documentation @ http://www.cplusplus.com/ sais following (c++98):

in fill version (2), new contents n elements, each initialized copy of val. if reallocation happens,the storage needed allocated using internal allocator.

any elements held in container before call destroyed , replaced newly constructed elements (no assignments of elements take place). causes automatic reallocation of allocated storage space if -and if- new vector size surpasses current vector capacity.

the phrase "no assignments of elements take place" make little confusing.

so example, want have vector of classes (for example, cv::vec3i of opencv). mean, that

  1. the destructor or constructor of cv::vec3i called?
  2. a direct copy of vec3i memory made , fills vector?
  3. what happens, if class allocates memory @ run time new operator? memory cannot accounted plain memory copying. mean, assign() should not used such objects?

edit: whole purpose of using assign in case set values in vector 0 (in case have std::vector< cv::vec3i > v). done many-many times. size of std::vector not changed.

what want (in shorter way) following:

 for(int i=0; i<v.size(); i++)      for(int j=0; j<3; j++)      v[i][j] = 0; 

right interested in c++98

i assume have vector filled data , call assign on it, will:

  1. destroy elements of vector (their destructor called) call clear()
  2. fill now-empty vector n copies of given object, must have copy constructor.

so if class allocates memory have to:

  1. take care of in copy constructor
  2. free in destructor

reallocations happen when size exceed allocated memory (vector capacity). can prevent call reserve(). think assign() smart enough allocate memory needs (if more allocated) before starting fill vector , after having cleared it.

you may want avoid reallocations because of cost, if trying avoid them because objects cannot handle properly, discourage put them in vector.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -