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
- the destructor or constructor of cv::vec3i called?
- a direct copy of vec3i memory made , fills vector?
- 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:
- destroy elements of vector (their destructor called) call clear()
- fill now-empty vector n copies of given object, must have copy constructor.
so if class allocates memory have to:
- take care of in copy constructor
- 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
Post a Comment