Monday 19 December 2016

c++ - What are the necessary special member functions that should to be declared?




I am currently learning about C++. I learnt about some special member functions which are generated by the compiler.




• Default constructor. • Copy constructor • Move Constructor • Copy assignment operator • Move assignment operator • Destructor



I know about the functionalities of each member function. But I wanna know which of these member function are necessary and should be declared (instead of being generated by the compiler), as a part of good coding practices, keeping memory and efficiency in mind.


Answer



The default constructor is a special case among these. If some member variables need an initial state that is not the default value of those members, write a default constructor.



The rest of these should really only be overwritten if you know that you need it.



These are some reasonable cases in which you might want to write custom versions of the listed functions:





  1. Your class has member variables that are pointers to dynamic memory that it has allocated.

  2. Your class has data structures as members that the user is not expected to pass completed versions of into the constructor.

  3. Your class has members that you do not want to use the default copy model for (e.g. you want a deep copy but the copy constructor or assignment would make a shallow copy).

  4. Your class has a static data member that should be changed when new instances of it are created.



Examples of each of these use cases include:





  1. STL vectors, which dynamically allocates its underlying array and deallocates in its destructor.

  2. STL lists, which copy data that is added to them onto list nodes, the internals of which are not exposed to the end-user.

  3. Any STL container class is a good example of this.

  4. Something where the number of things which need access to an expensive resource are needed. Similar to the design goal of a std::shared_ptr.



If one class meets too many of these requirements, you should probably consider changing your design to use more of the containers an utilities provided by the standard library. Especially if one class requires the fourth property and any of the other three. The responsibilities related to points 1-3 and point 4 should be handled by different classes. It is important to note that ownership of one large, expensive-to-create resource and ownership of many resources are different types of responsibility.



References:





No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...