Copy constructor for object with vector fo object as member variable

删除回忆录丶 提交于 2019-12-10 11:49:10

问题


I have a class A with a vector<Object> object_list_ as a member variable.

I know that if I had a vector of pointers I would have needed to write a specific copy constructor to achieve a deep copy. However, in this case, as I don't have pointers, when copying an object of type A, the default copy constructor will automatically also call the copy constructors of Object or each element in object_list_ or do I have to write my own copy constructor to do that?


回答1:


The default copy constructor for your class will call the default copy constructor for each member, in the order they're declared in the class. One rule of thumb is that if you don't need a special destructor, then you don't need to change the copy constructor, copy assignment, move constructor, or move assignment either. (Though deleting them may still make sense, depending on the class).

A vector's copy constructor will make a copy of its elements, using their copy constructors. If those are pointers, it will copy the pointers, which means they'll point at the same data as the origonal vector. 99% of the time this is what you want. Though very rarely you may want to replace your class' copy constructor to make the vector do something else.

It sounds like you don't need to make a copy constructor in your case.




回答2:


Copy constructors of member variables are called all the way down. So if a default one was generated (and it would be in this case) then it gets called.



来源:https://stackoverflow.com/questions/29262732/copy-constructor-for-object-with-vector-fo-object-as-member-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!