Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are copy constructors required for classes which have vector, list or map from the stl as members

I am writing a class which uses the stl class map as a member. I have no pointers in the class. Do I need to write a custom copy constructor or will the default copy constructor work fine?

After reading the answers I am adding some more information. I have static const variables but those are not initialized during construction. I have no reference members. Everything else is a 64 bit integer. I also have a map iterator as a member in the class.

like image 949
Zachary Kraus Avatar asked Aug 20 '14 19:08

Zachary Kraus


1 Answers

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

Generally speaking, the only time you may have an issue is when you are using members that carry non-trivial construction/destruction (like objects that manage a global resource such as file descriptors for files/kernel services and pointers for memory) that would be (and need to be) cleaned up by the destructor and reallocated by the copy constructor.

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

like image 143
randomusername Avatar answered Sep 28 '22 00:09

randomusername