Storing objects in the STL vector - the minimum set of methods

What is the "minimal structure" (necessary methods) of a complex object (with explicitly specified internal data) that I want to store in an STL container, for example. <vector> ?

For my guesses (an example of a complex Doit object):

 #include <vector> #include <cstring> using namespace std; class Doit { private: char *a; public: Doit(){a=(char*)malloc(10);} ~Doit(){free(a);} }; int main(){ vector<Doit> v(10); } 

gives

 *** glibc detected *** ./a.out: double free or corruption (fasttop): 0x0804b008 *** Aborted 

and in valgrind:

 malloc/free: 2 allocs, 12 frees, 50 bytes allocated. 

UPDATE:

Minimum methods for such an object: (based on sbi's answer)

 class DoIt{ private: char *a; public: DoIt() { a=new char[10]; } ~DoIt() { delete[] a; } DoIt(const DoIt& rhs) { a=new char[10]; std::copy(rhs.a,rhs.a+10,a); } DoIt& operator=(const DoIt& rhs) { DoIt tmp(rhs); swap(tmp); return *this;} void swap(DoIt& rhs) { std::swap(a,rhs.a); } }; 

Thanks, sbi, https://stackoverflow.com/users/140719/sbi

+6
c ++ copy-constructor rule-of-three stl
source share
3 answers

Please note that Charles answered your question perfectly.

In any case, according to Rule three , your class that has a destructor must have a copy constructor and an assignment operator too,

Here is how I would do it:

 class Doit { private: char *a; public: Doit() : a(new char[10]) {} ~Doit() {delete[] a;} DoIt(const DoIt& rhs) : a(new char[10]) {std::copy(rhs.a,rhs.a+10,a);} void swap(DoIt& rhs) {std::swap(a,rhs.a);} DoIt& operator=(DoIt rhs) {swap(rhs); return *this;} }; 
+10
source share

All types you use must be CopyConstructible and Assignable .

CopyConstructible for type T means that if T is T or const T , then the expression T(t) should lead to the equivalent of T to the original T ; t. ~ T () must be valid (available destructor); and &t should indicate the address T as [const] T* .

Assignable means that for the values ​​of T , T and a T u expression t = u should make T equivalent to u and be of type T& .

Note that all these requirements are met with simple built-in types and POD structures. If you are doing something non-trivial in a destructor or constructor, you must make sure that the copy operator and copy assignment operator retain the semantics of equivalence.

+6
source share

Everything vector requires the object to be β€œassignable,” which means that it needs a constructor statement, destructor, and assignment operator, which are all generated by default if you don't supply them yourself.

As sbi says, if you need one of these functions, you probably need all of them. In your case, you also need to provide a copy constructor and an assignment operator to avoid damage to the heap.

0
source share

All Articles