Copy constructors are required for classes that have a vector, list or map from stl as members

I am writing a class that uses stl class map as member. I have no pointers in the class. Should I write my own copy constructor, or does the default copy constructor work fine?

After reading the answers, I add more information. I have static const variables, but they are not initialized at build time. I have no reference members. Everything else is a 64 bit integer. I also have a map iterator as a member of the class.

+3


source to share


4 answers


The default copy constructor will always work (it just calls the copy constructors of all class members).

Generally speaking, the only time you might have a problem is you use members that carry non-trivial construction / destruction (for example, objects that manage a global resource such as file descriptors for kernel files / services and memory pointers) which will (and should be) cleaned up by the destructor and redistributed by the copy constructor.



I know of some optimizations that can make the copy constructor faster if you implement it, but they really aren't needed.

+4


source


Pointer members aren't the only things that can cause problems here. There are several factors that may require you to have a custom copy constructor, including but not limited to:



  • Link elements as they require explicit initialization
  • const

    member variables, same reason
  • Any member variables of types that do not provide copy constructors
+3


source


The default copy constructor will work fine.

+1


source


There is a way in C ++ to prevent copying of an object of a certain type. Well-written libraries, including the STL, only allow types to be copied if they are safe and make sense for that type. So if you can copy it (the compiler doesn't generate errors) then it is safe. It is good practice to follow this in your own program, even if it is not that big.

+1


source







All Articles